es6.js 4.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. this._loadVertexShader(vertexSource, function (vertexCode) {
  143. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  144. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  145. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  146. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  147. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  148. if (baseName) {
  149. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  150. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  151. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  152. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  153. }
  154. else {
  155. _this._vertexSourceCode = migratedVertexCode;
  156. _this._fragmentSourceCode = migratedFragmentCode;
  157. }
  158. _this._prepareEffect();
  159. });
  160. });
  161. });
  162. });
  163. });
  164. });
  165. }
  166. Object.defineProperty(Effect.prototype, "key", {
  167. get: function () {
  168. return this._key;
  169. },
  170. enumerable: true,
  171. configurable: true
  172. });
  173. // Properties
  174. Effect.prototype.isReady = function () {
  175. return this._isReady;
  176. };
  177. Effect.prototype.getEngine = function () {
  178. return this._engine;
  179. };
  180. Effect.prototype.getProgram = function () {
  181. return this._program;
  182. };
  183. Effect.prototype.getAttributesNames = function () {
  184. return this._attributesNames;
  185. };
  186. Effect.prototype.getAttributeLocation = function (index) {
  187. return this._attributes[index];
  188. };
  189. Effect.prototype.getAttributeLocationByName = function (name) {
  190. var index = this._attributesNames.indexOf(name);
  191. return this._attributes[index];
  192. };
  193. Effect.prototype.getAttributesCount = function () {
  194. return this._attributes.length;
  195. };
  196. Effect.prototype.getUniformIndex = function (uniformName) {
  197. return this._uniformsNames.indexOf(uniformName);
  198. };
  199. Effect.prototype.getUniform = function (uniformName) {
  200. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  201. };
  202. Effect.prototype.getSamplers = function () {
  203. return this._samplers;
  204. };
  205. Effect.prototype.getCompilationError = function () {
  206. return this._compilationError;
  207. };
  208. // Methods
  209. Effect.prototype.executeWhenCompiled = function (func) {
  210. if (this.isReady()) {
  211. func(this);
  212. return;
  213. }
  214. this.onCompileObservable.add(function (effect) {
  215. func(effect);
  216. });
  217. };
  218. Effect.prototype._loadVertexShader = function (vertex, callback) {
  219. if (BABYLON.Tools.IsWindowObjectExist()) {
  220. // DOM element ?
  221. if (vertex instanceof HTMLElement) {
  222. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  223. callback(vertexCode);
  224. return;
  225. }
  226. }
  227. // Base64 encoded ?
  228. if (vertex.substr(0, 7) === "base64:") {
  229. var vertexBinary = window.atob(vertex.substr(7));
  230. callback(vertexBinary);
  231. return;
  232. }
  233. // Is in local store ?
  234. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  235. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  236. return;
  237. }
  238. var vertexShaderUrl;
  239. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  240. vertexShaderUrl = vertex;
  241. }
  242. else {
  243. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  244. }
  245. // Vertex shader
  246. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  247. };
  248. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  249. if (BABYLON.Tools.IsWindowObjectExist()) {
  250. // DOM element ?
  251. if (fragment instanceof HTMLElement) {
  252. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  253. callback(fragmentCode);
  254. return;
  255. }
  256. }
  257. // Base64 encoded ?
  258. if (fragment.substr(0, 7) === "base64:") {
  259. var fragmentBinary = window.atob(fragment.substr(7));
  260. callback(fragmentBinary);
  261. return;
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  266. return;
  267. }
  268. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  269. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  270. return;
  271. }
  272. var fragmentShaderUrl;
  273. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  274. fragmentShaderUrl = fragment;
  275. }
  276. else {
  277. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  278. }
  279. // Fragment shader
  280. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  281. };
  282. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  283. // Rebuild shaders source code
  284. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  285. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  286. vertexCode = prefix + vertexCode;
  287. fragmentCode = prefix + fragmentCode;
  288. // Number lines of shaders source code
  289. var i = 2;
  290. var regex = /\n/gm;
  291. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. i = 2;
  293. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  294. // Dump shaders name and formatted source code
  295. if (this.name.vertexElement) {
  296. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  297. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  298. }
  299. else if (this.name.vertex) {
  300. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  301. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  302. }
  303. else {
  304. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  305. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  306. }
  307. };
  308. ;
  309. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  310. var preparedSourceCode = this._processPrecision(sourceCode);
  311. if (this._engine.webGLVersion == 1) {
  312. callback(preparedSourceCode);
  313. return;
  314. }
  315. // Already converted
  316. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  317. callback(preparedSourceCode.replace("#version 300 es", ""));
  318. return;
  319. }
  320. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  321. // Remove extensions
  322. // #extension GL_OES_standard_derivatives : enable
  323. // #extension GL_EXT_shader_texture_lod : enable
  324. // #extension GL_EXT_frag_depth : enable
  325. // #extension GL_EXT_draw_buffers : require
  326. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  327. var result = preparedSourceCode.replace(regex, "");
  328. // Migrate to GLSL v300
  329. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  330. result = result.replace(/attribute[ \t]/g, "in ");
  331. result = result.replace(/[ \t]attribute/g, " in");
  332. if (isFragment) {
  333. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  334. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  335. result = result.replace(/texture2D\s*\(/g, "texture(");
  336. result = result.replace(/textureCube\s*\(/g, "texture(");
  337. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  338. result = result.replace(/gl_FragColor/g, "glFragColor");
  339. result = result.replace(/gl_FragData/g, "glFragData");
  340. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  341. }
  342. callback(result);
  343. };
  344. Effect.prototype._processIncludes = function (sourceCode, callback) {
  345. var _this = this;
  346. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  347. var match = regex.exec(sourceCode);
  348. var returnValue = new String(sourceCode);
  349. while (match != null) {
  350. var includeFile = match[1];
  351. // Uniform declaration
  352. if (includeFile.indexOf("__decl__") !== -1) {
  353. includeFile = includeFile.replace(/__decl__/, "");
  354. if (this._engine.supportsUniformBuffers) {
  355. includeFile = includeFile.replace(/Vertex/, "Ubo");
  356. includeFile = includeFile.replace(/Fragment/, "Ubo");
  357. }
  358. includeFile = includeFile + "Declaration";
  359. }
  360. if (Effect.IncludesShadersStore[includeFile]) {
  361. // Substitution
  362. var includeContent = Effect.IncludesShadersStore[includeFile];
  363. if (match[2]) {
  364. var splits = match[3].split(",");
  365. for (var index = 0; index < splits.length; index += 2) {
  366. var source = new RegExp(splits[index], "g");
  367. var dest = splits[index + 1];
  368. includeContent = includeContent.replace(source, dest);
  369. }
  370. }
  371. if (match[4]) {
  372. var indexString = match[5];
  373. if (indexString.indexOf("..") !== -1) {
  374. var indexSplits = indexString.split("..");
  375. var minIndex = parseInt(indexSplits[0]);
  376. var maxIndex = parseInt(indexSplits[1]);
  377. var sourceIncludeContent = includeContent.slice(0);
  378. includeContent = "";
  379. if (isNaN(maxIndex)) {
  380. maxIndex = this._indexParameters[indexSplits[1]];
  381. }
  382. for (var i = minIndex; i < maxIndex; i++) {
  383. if (!this._engine.supportsUniformBuffers) {
  384. // Ubo replacement
  385. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  386. return p1 + "{X}";
  387. });
  388. }
  389. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  390. }
  391. }
  392. else {
  393. if (!this._engine.supportsUniformBuffers) {
  394. // Ubo replacement
  395. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  396. return p1 + "{X}";
  397. });
  398. }
  399. includeContent = includeContent.replace(/\{X\}/g, indexString);
  400. }
  401. }
  402. // Replace
  403. returnValue = returnValue.replace(match[0], includeContent);
  404. }
  405. else {
  406. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  407. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  408. Effect.IncludesShadersStore[includeFile] = fileContent;
  409. _this._processIncludes(returnValue, callback);
  410. });
  411. return;
  412. }
  413. match = regex.exec(sourceCode);
  414. }
  415. callback(returnValue);
  416. };
  417. Effect.prototype._processPrecision = function (source) {
  418. if (source.indexOf("precision highp float") === -1) {
  419. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  420. source = "precision mediump float;\n" + source;
  421. }
  422. else {
  423. source = "precision highp float;\n" + source;
  424. }
  425. }
  426. else {
  427. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  428. source = source.replace("precision highp float", "precision mediump float");
  429. }
  430. }
  431. return source;
  432. };
  433. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  434. var _this = this;
  435. this._isReady = false;
  436. this._vertexSourceCodeOverride = vertexSourceCode;
  437. this._fragmentSourceCodeOverride = fragmentSourceCode;
  438. this.onError = function (effect, error) {
  439. if (onError) {
  440. onError(error);
  441. }
  442. };
  443. this.onCompiled = function () {
  444. var scenes = _this.getEngine().scenes;
  445. for (var i = 0; i < scenes.length; i++) {
  446. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  447. }
  448. if (onCompiled) {
  449. onCompiled(_this._program);
  450. }
  451. };
  452. this._fallbacks = null;
  453. this._prepareEffect();
  454. };
  455. Effect.prototype.getSpecificUniformLocations = function (names) {
  456. var engine = this._engine;
  457. return engine.getUniforms(this._program, names);
  458. };
  459. Effect.prototype._prepareEffect = function () {
  460. var attributesNames = this._attributesNames;
  461. var defines = this.defines;
  462. var fallbacks = this._fallbacks;
  463. this._valueCache = {};
  464. var previousProgram = this._program;
  465. try {
  466. var engine = this._engine;
  467. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  468. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  469. }
  470. else {
  471. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  472. }
  473. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  474. if (engine.supportsUniformBuffers) {
  475. for (var name in this._uniformBuffersNames) {
  476. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  477. }
  478. }
  479. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  480. this._attributes = engine.getAttributes(this._program, attributesNames);
  481. var index;
  482. for (index = 0; index < this._samplers.length; index++) {
  483. var sampler = this.getUniform(this._samplers[index]);
  484. if (sampler == null) {
  485. this._samplers.splice(index, 1);
  486. index--;
  487. }
  488. }
  489. engine.bindSamplers(this);
  490. this._compilationError = "";
  491. this._isReady = true;
  492. if (this.onCompiled) {
  493. this.onCompiled(this);
  494. }
  495. this.onCompileObservable.notifyObservers(this);
  496. this.onCompileObservable.clear();
  497. // Unbind mesh reference in fallbacks
  498. if (this._fallbacks) {
  499. this._fallbacks.unBindMesh();
  500. }
  501. if (previousProgram) {
  502. this.getEngine()._deleteProgram(previousProgram);
  503. }
  504. }
  505. catch (e) {
  506. this._compilationError = e.message;
  507. // Let's go through fallbacks then
  508. BABYLON.Tools.Error("Unable to compile effect:");
  509. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  510. return " " + uniform;
  511. }));
  512. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  513. return " " + attribute;
  514. }));
  515. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  516. BABYLON.Tools.Error("Error: " + this._compilationError);
  517. if (previousProgram) {
  518. this._program = previousProgram;
  519. this._isReady = true;
  520. if (this.onError) {
  521. this.onError(this, this._compilationError);
  522. }
  523. this.onErrorObservable.notifyObservers(this);
  524. }
  525. if (fallbacks && fallbacks.isMoreFallbacks) {
  526. BABYLON.Tools.Error("Trying next fallback.");
  527. this.defines = fallbacks.reduce(this.defines);
  528. this._prepareEffect();
  529. }
  530. else {
  531. if (this.onError) {
  532. this.onError(this, this._compilationError);
  533. }
  534. this.onErrorObservable.notifyObservers(this);
  535. this.onErrorObservable.clear();
  536. // Unbind mesh reference in fallbacks
  537. if (this._fallbacks) {
  538. this._fallbacks.unBindMesh();
  539. }
  540. }
  541. }
  542. };
  543. Object.defineProperty(Effect.prototype, "isSupported", {
  544. get: function () {
  545. return this._compilationError === "";
  546. },
  547. enumerable: true,
  548. configurable: true
  549. });
  550. Effect.prototype._bindTexture = function (channel, texture) {
  551. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  552. };
  553. Effect.prototype.setTexture = function (channel, texture) {
  554. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  555. };
  556. Effect.prototype.setTextureArray = function (channel, textures) {
  557. if (this._samplers.indexOf(channel + "Ex") === -1) {
  558. var initialPos = this._samplers.indexOf(channel);
  559. for (var index = 1; index < textures.length; index++) {
  560. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  561. }
  562. }
  563. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  564. };
  565. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  566. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  567. };
  568. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  569. var cache = this._valueCache[uniformName];
  570. var flag = matrix.updateFlag;
  571. if (cache !== undefined && cache === flag) {
  572. return false;
  573. }
  574. this._valueCache[uniformName] = flag;
  575. return true;
  576. };
  577. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  578. var cache = this._valueCache[uniformName];
  579. if (!cache) {
  580. cache = [x, y];
  581. this._valueCache[uniformName] = cache;
  582. return true;
  583. }
  584. var changed = false;
  585. if (cache[0] !== x) {
  586. cache[0] = x;
  587. changed = true;
  588. }
  589. if (cache[1] !== y) {
  590. cache[1] = y;
  591. changed = true;
  592. }
  593. return changed;
  594. };
  595. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  596. var cache = this._valueCache[uniformName];
  597. if (!cache) {
  598. cache = [x, y, z];
  599. this._valueCache[uniformName] = cache;
  600. return true;
  601. }
  602. var changed = false;
  603. if (cache[0] !== x) {
  604. cache[0] = x;
  605. changed = true;
  606. }
  607. if (cache[1] !== y) {
  608. cache[1] = y;
  609. changed = true;
  610. }
  611. if (cache[2] !== z) {
  612. cache[2] = z;
  613. changed = true;
  614. }
  615. return changed;
  616. };
  617. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  618. var cache = this._valueCache[uniformName];
  619. if (!cache) {
  620. cache = [x, y, z, w];
  621. this._valueCache[uniformName] = cache;
  622. return true;
  623. }
  624. var changed = false;
  625. if (cache[0] !== x) {
  626. cache[0] = x;
  627. changed = true;
  628. }
  629. if (cache[1] !== y) {
  630. cache[1] = y;
  631. changed = true;
  632. }
  633. if (cache[2] !== z) {
  634. cache[2] = z;
  635. changed = true;
  636. }
  637. if (cache[3] !== w) {
  638. cache[3] = w;
  639. changed = true;
  640. }
  641. return changed;
  642. };
  643. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  644. var bufferName = this._uniformBuffersNames[name];
  645. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  646. return;
  647. }
  648. Effect._baseCache[bufferName] = buffer;
  649. this._engine.bindUniformBufferBase(buffer, bufferName);
  650. };
  651. Effect.prototype.bindUniformBlock = function (blockName, index) {
  652. this._engine.bindUniformBlock(this._program, blockName, index);
  653. };
  654. Effect.prototype.setInt = function (uniformName, value) {
  655. var cache = this._valueCache[uniformName];
  656. if (cache !== undefined && cache === value)
  657. return this;
  658. this._valueCache[uniformName] = value;
  659. this._engine.setInt(this.getUniform(uniformName), value);
  660. return this;
  661. };
  662. Effect.prototype.setIntArray = function (uniformName, array) {
  663. this._valueCache[uniformName] = null;
  664. this._engine.setIntArray(this.getUniform(uniformName), array);
  665. return this;
  666. };
  667. Effect.prototype.setIntArray2 = function (uniformName, array) {
  668. this._valueCache[uniformName] = null;
  669. this._engine.setIntArray2(this.getUniform(uniformName), array);
  670. return this;
  671. };
  672. Effect.prototype.setIntArray3 = function (uniformName, array) {
  673. this._valueCache[uniformName] = null;
  674. this._engine.setIntArray3(this.getUniform(uniformName), array);
  675. return this;
  676. };
  677. Effect.prototype.setIntArray4 = function (uniformName, array) {
  678. this._valueCache[uniformName] = null;
  679. this._engine.setIntArray4(this.getUniform(uniformName), array);
  680. return this;
  681. };
  682. Effect.prototype.setFloatArray = function (uniformName, array) {
  683. this._valueCache[uniformName] = null;
  684. this._engine.setFloatArray(this.getUniform(uniformName), array);
  685. return this;
  686. };
  687. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  688. this._valueCache[uniformName] = null;
  689. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  690. return this;
  691. };
  692. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  693. this._valueCache[uniformName] = null;
  694. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  695. return this;
  696. };
  697. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  698. this._valueCache[uniformName] = null;
  699. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  700. return this;
  701. };
  702. Effect.prototype.setArray = function (uniformName, array) {
  703. this._valueCache[uniformName] = null;
  704. this._engine.setArray(this.getUniform(uniformName), array);
  705. return this;
  706. };
  707. Effect.prototype.setArray2 = function (uniformName, array) {
  708. this._valueCache[uniformName] = null;
  709. this._engine.setArray2(this.getUniform(uniformName), array);
  710. return this;
  711. };
  712. Effect.prototype.setArray3 = function (uniformName, array) {
  713. this._valueCache[uniformName] = null;
  714. this._engine.setArray3(this.getUniform(uniformName), array);
  715. return this;
  716. };
  717. Effect.prototype.setArray4 = function (uniformName, array) {
  718. this._valueCache[uniformName] = null;
  719. this._engine.setArray4(this.getUniform(uniformName), array);
  720. return this;
  721. };
  722. Effect.prototype.setMatrices = function (uniformName, matrices) {
  723. if (!matrices) {
  724. return this;
  725. }
  726. this._valueCache[uniformName] = null;
  727. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  728. return this;
  729. };
  730. Effect.prototype.setMatrix = function (uniformName, matrix) {
  731. if (this._cacheMatrix(uniformName, matrix)) {
  732. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  733. }
  734. return this;
  735. };
  736. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  737. this._valueCache[uniformName] = null;
  738. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  739. return this;
  740. };
  741. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  744. return this;
  745. };
  746. Effect.prototype.setFloat = function (uniformName, value) {
  747. var cache = this._valueCache[uniformName];
  748. if (cache !== undefined && cache === value)
  749. return this;
  750. this._valueCache[uniformName] = value;
  751. this._engine.setFloat(this.getUniform(uniformName), value);
  752. return this;
  753. };
  754. Effect.prototype.setBool = function (uniformName, bool) {
  755. var cache = this._valueCache[uniformName];
  756. if (cache !== undefined && cache === bool)
  757. return this;
  758. this._valueCache[uniformName] = bool;
  759. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  760. return this;
  761. };
  762. Effect.prototype.setVector2 = function (uniformName, vector2) {
  763. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  764. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  765. }
  766. return this;
  767. };
  768. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  769. if (this._cacheFloat2(uniformName, x, y)) {
  770. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  771. }
  772. return this;
  773. };
  774. Effect.prototype.setVector3 = function (uniformName, vector3) {
  775. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  776. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  777. }
  778. return this;
  779. };
  780. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  781. if (this._cacheFloat3(uniformName, x, y, z)) {
  782. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  783. }
  784. return this;
  785. };
  786. Effect.prototype.setVector4 = function (uniformName, vector4) {
  787. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  788. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  789. }
  790. return this;
  791. };
  792. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  793. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  794. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  795. }
  796. return this;
  797. };
  798. Effect.prototype.setColor3 = function (uniformName, color3) {
  799. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  800. this._engine.setColor3(this.getUniform(uniformName), color3);
  801. }
  802. return this;
  803. };
  804. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  805. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  806. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  807. }
  808. return this;
  809. };
  810. Effect.ResetCache = function () {
  811. Effect._baseCache = {};
  812. };
  813. Effect._uniqueIdSeed = 0;
  814. Effect._baseCache = {};
  815. // Statics
  816. Effect.ShadersStore = {};
  817. Effect.IncludesShadersStore = {};
  818. return Effect;
  819. }());
  820. BABYLON.Effect = Effect;
  821. })(BABYLON || (BABYLON = {}));
  822. //# sourceMappingURL=babylon.effect.js.map
  823. //# sourceMappingURL=babylon.types.js.map
  824. var BABYLON;
  825. (function (BABYLON) {
  826. var KeyboardEventTypes = /** @class */ (function () {
  827. function KeyboardEventTypes() {
  828. }
  829. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  830. get: function () {
  831. return KeyboardEventTypes._KEYDOWN;
  832. },
  833. enumerable: true,
  834. configurable: true
  835. });
  836. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  837. get: function () {
  838. return KeyboardEventTypes._KEYUP;
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. KeyboardEventTypes._KEYDOWN = 0x01;
  844. KeyboardEventTypes._KEYUP = 0x02;
  845. return KeyboardEventTypes;
  846. }());
  847. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  848. var KeyboardInfo = /** @class */ (function () {
  849. function KeyboardInfo(type, event) {
  850. this.type = type;
  851. this.event = event;
  852. }
  853. return KeyboardInfo;
  854. }());
  855. BABYLON.KeyboardInfo = KeyboardInfo;
  856. /**
  857. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  858. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  859. */
  860. var KeyboardInfoPre = /** @class */ (function (_super) {
  861. __extends(KeyboardInfoPre, _super);
  862. function KeyboardInfoPre(type, event) {
  863. var _this = _super.call(this, type, event) || this;
  864. _this.skipOnPointerObservable = false;
  865. return _this;
  866. }
  867. return KeyboardInfoPre;
  868. }(KeyboardInfo));
  869. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  870. })(BABYLON || (BABYLON = {}));
  871. //# sourceMappingURL=babylon.keyboardEvents.js.map
  872. var BABYLON;
  873. (function (BABYLON) {
  874. var PointerEventTypes = /** @class */ (function () {
  875. function PointerEventTypes() {
  876. }
  877. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  878. get: function () {
  879. return PointerEventTypes._POINTERDOWN;
  880. },
  881. enumerable: true,
  882. configurable: true
  883. });
  884. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  885. get: function () {
  886. return PointerEventTypes._POINTERUP;
  887. },
  888. enumerable: true,
  889. configurable: true
  890. });
  891. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  892. get: function () {
  893. return PointerEventTypes._POINTERMOVE;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  899. get: function () {
  900. return PointerEventTypes._POINTERWHEEL;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  906. get: function () {
  907. return PointerEventTypes._POINTERPICK;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  913. get: function () {
  914. return PointerEventTypes._POINTERTAP;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  920. get: function () {
  921. return PointerEventTypes._POINTERDOUBLETAP;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. PointerEventTypes._POINTERDOWN = 0x01;
  927. PointerEventTypes._POINTERUP = 0x02;
  928. PointerEventTypes._POINTERMOVE = 0x04;
  929. PointerEventTypes._POINTERWHEEL = 0x08;
  930. PointerEventTypes._POINTERPICK = 0x10;
  931. PointerEventTypes._POINTERTAP = 0x20;
  932. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  933. return PointerEventTypes;
  934. }());
  935. BABYLON.PointerEventTypes = PointerEventTypes;
  936. var PointerInfoBase = /** @class */ (function () {
  937. function PointerInfoBase(type, event) {
  938. this.type = type;
  939. this.event = event;
  940. }
  941. return PointerInfoBase;
  942. }());
  943. BABYLON.PointerInfoBase = PointerInfoBase;
  944. /**
  945. * This class is used to store pointer related info for the onPrePointerObservable event.
  946. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  947. */
  948. var PointerInfoPre = /** @class */ (function (_super) {
  949. __extends(PointerInfoPre, _super);
  950. function PointerInfoPre(type, event, localX, localY) {
  951. var _this = _super.call(this, type, event) || this;
  952. _this.skipOnPointerObservable = false;
  953. _this.localPosition = new BABYLON.Vector2(localX, localY);
  954. return _this;
  955. }
  956. return PointerInfoPre;
  957. }(PointerInfoBase));
  958. BABYLON.PointerInfoPre = PointerInfoPre;
  959. /**
  960. * This type contains all the data related to a pointer event in Babylon.js.
  961. * 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.
  962. */
  963. var PointerInfo = /** @class */ (function (_super) {
  964. __extends(PointerInfo, _super);
  965. function PointerInfo(type, event, pickInfo) {
  966. var _this = _super.call(this, type, event) || this;
  967. _this.pickInfo = pickInfo;
  968. return _this;
  969. }
  970. return PointerInfo;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfo = PointerInfo;
  973. })(BABYLON || (BABYLON = {}));
  974. //# sourceMappingURL=babylon.pointerEvents.js.map
  975. var BABYLON;
  976. (function (BABYLON) {
  977. BABYLON.ToGammaSpace = 1 / 2.2;
  978. BABYLON.ToLinearSpace = 2.2;
  979. BABYLON.Epsilon = 0.001;
  980. var Color3 = /** @class */ (function () {
  981. /**
  982. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  983. */
  984. function Color3(r, g, b) {
  985. if (r === void 0) { r = 0; }
  986. if (g === void 0) { g = 0; }
  987. if (b === void 0) { b = 0; }
  988. this.r = r;
  989. this.g = g;
  990. this.b = b;
  991. }
  992. /**
  993. * Returns a string with the Color3 current values.
  994. */
  995. Color3.prototype.toString = function () {
  996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  997. };
  998. /**
  999. * Returns the string "Color3".
  1000. */
  1001. Color3.prototype.getClassName = function () {
  1002. return "Color3";
  1003. };
  1004. /**
  1005. * Returns the Color3 hash code.
  1006. */
  1007. Color3.prototype.getHashCode = function () {
  1008. var hash = this.r || 0;
  1009. hash = (hash * 397) ^ (this.g || 0);
  1010. hash = (hash * 397) ^ (this.b || 0);
  1011. return hash;
  1012. };
  1013. // Operators
  1014. /**
  1015. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1016. * Returns the Color3.
  1017. */
  1018. Color3.prototype.toArray = function (array, index) {
  1019. if (index === undefined) {
  1020. index = 0;
  1021. }
  1022. array[index] = this.r;
  1023. array[index + 1] = this.g;
  1024. array[index + 2] = this.b;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1029. */
  1030. Color3.prototype.toColor4 = function (alpha) {
  1031. if (alpha === void 0) { alpha = 1; }
  1032. return new Color4(this.r, this.g, this.b, alpha);
  1033. };
  1034. /**
  1035. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1036. */
  1037. Color3.prototype.asArray = function () {
  1038. var result = new Array();
  1039. this.toArray(result, 0);
  1040. return result;
  1041. };
  1042. /**
  1043. * Returns the luminance value (float).
  1044. */
  1045. Color3.prototype.toLuminance = function () {
  1046. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1047. };
  1048. /**
  1049. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1050. * Returns this new object.
  1051. */
  1052. Color3.prototype.multiply = function (otherColor) {
  1053. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1054. };
  1055. /**
  1056. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1057. * Returns the current Color3.
  1058. */
  1059. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1060. result.r = this.r * otherColor.r;
  1061. result.g = this.g * otherColor.g;
  1062. result.b = this.b * otherColor.b;
  1063. return this;
  1064. };
  1065. /**
  1066. * Boolean : True if the rgb values are equal to the passed ones.
  1067. */
  1068. Color3.prototype.equals = function (otherColor) {
  1069. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1070. };
  1071. /**
  1072. * Boolean : True if the rgb values are equal to the passed ones.
  1073. */
  1074. Color3.prototype.equalsFloats = function (r, g, b) {
  1075. return this.r === r && this.g === g && this.b === b;
  1076. };
  1077. /**
  1078. * Multiplies in place each rgb value by scale.
  1079. * Returns the updated Color3.
  1080. */
  1081. Color3.prototype.scale = function (scale) {
  1082. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1083. };
  1084. /**
  1085. * Multiplies the rgb values by scale and stores the result into "result".
  1086. * Returns the unmodified current Color3.
  1087. */
  1088. Color3.prototype.scaleToRef = function (scale, result) {
  1089. result.r = this.r * scale;
  1090. result.g = this.g * scale;
  1091. result.b = this.b * scale;
  1092. return this;
  1093. };
  1094. /**
  1095. * Clamps the rgb values by the min and max values and stores the result into "result".
  1096. * Returns the unmodified current Color3.
  1097. * @param min - minimum clamping value. Defaults to 0
  1098. * @param max - maximum clamping value. Defaults to 1
  1099. * @param result - color to store the result into.
  1100. * @returns - the original Color3
  1101. */
  1102. Color3.prototype.clampToRef = function (min, max, result) {
  1103. if (min === void 0) { min = 0; }
  1104. if (max === void 0) { max = 1; }
  1105. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1106. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1107. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1108. return this;
  1109. };
  1110. /**
  1111. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1112. */
  1113. Color3.prototype.add = function (otherColor) {
  1114. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1115. };
  1116. /**
  1117. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1118. * Returns the unmodified current Color3.
  1119. */
  1120. Color3.prototype.addToRef = function (otherColor, result) {
  1121. result.r = this.r + otherColor.r;
  1122. result.g = this.g + otherColor.g;
  1123. result.b = this.b + otherColor.b;
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1128. */
  1129. Color3.prototype.subtract = function (otherColor) {
  1130. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1131. };
  1132. /**
  1133. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1134. * Returns the unmodified current Color3.
  1135. */
  1136. Color3.prototype.subtractToRef = function (otherColor, result) {
  1137. result.r = this.r - otherColor.r;
  1138. result.g = this.g - otherColor.g;
  1139. result.b = this.b - otherColor.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Returns a new Color3 copied the current one.
  1144. */
  1145. Color3.prototype.clone = function () {
  1146. return new Color3(this.r, this.g, this.b);
  1147. };
  1148. /**
  1149. * Copies the rgb values from the source in the current Color3.
  1150. * Returns the updated Color3.
  1151. */
  1152. Color3.prototype.copyFrom = function (source) {
  1153. this.r = source.r;
  1154. this.g = source.g;
  1155. this.b = source.b;
  1156. return this;
  1157. };
  1158. /**
  1159. * Updates the Color3 rgb values from the passed floats.
  1160. * Returns the Color3.
  1161. */
  1162. Color3.prototype.copyFromFloats = function (r, g, b) {
  1163. this.r = r;
  1164. this.g = g;
  1165. this.b = b;
  1166. return this;
  1167. };
  1168. /**
  1169. * Updates the Color3 rgb values from the passed floats.
  1170. * Returns the Color3.
  1171. */
  1172. Color3.prototype.set = function (r, g, b) {
  1173. return this.copyFromFloats(r, g, b);
  1174. };
  1175. /**
  1176. * Returns the Color3 hexadecimal code as a string.
  1177. */
  1178. Color3.prototype.toHexString = function () {
  1179. var intR = (this.r * 255) | 0;
  1180. var intG = (this.g * 255) | 0;
  1181. var intB = (this.b * 255) | 0;
  1182. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1183. };
  1184. /**
  1185. * Returns a new Color3 converted to linear space.
  1186. */
  1187. Color3.prototype.toLinearSpace = function () {
  1188. var convertedColor = new Color3();
  1189. this.toLinearSpaceToRef(convertedColor);
  1190. return convertedColor;
  1191. };
  1192. /**
  1193. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1194. * Returns the unmodified Color3.
  1195. */
  1196. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1197. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1198. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1199. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1200. return this;
  1201. };
  1202. /**
  1203. * Returns a new Color3 converted to gamma space.
  1204. */
  1205. Color3.prototype.toGammaSpace = function () {
  1206. var convertedColor = new Color3();
  1207. this.toGammaSpaceToRef(convertedColor);
  1208. return convertedColor;
  1209. };
  1210. /**
  1211. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1212. * Returns the unmodified Color3.
  1213. */
  1214. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1215. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1216. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1217. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1218. return this;
  1219. };
  1220. // Statics
  1221. /**
  1222. * Creates a new Color3 from the string containing valid hexadecimal values.
  1223. */
  1224. Color3.FromHexString = function (hex) {
  1225. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1226. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1227. return new Color3(0, 0, 0);
  1228. }
  1229. var r = parseInt(hex.substring(1, 3), 16);
  1230. var g = parseInt(hex.substring(3, 5), 16);
  1231. var b = parseInt(hex.substring(5, 7), 16);
  1232. return Color3.FromInts(r, g, b);
  1233. };
  1234. /**
  1235. * Creates a new Vector3 from the startind index of the passed array.
  1236. */
  1237. Color3.FromArray = function (array, offset) {
  1238. if (offset === void 0) { offset = 0; }
  1239. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1240. };
  1241. /**
  1242. * Creates a new Color3 from integer values ( < 256).
  1243. */
  1244. Color3.FromInts = function (r, g, b) {
  1245. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1246. };
  1247. /**
  1248. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1249. */
  1250. Color3.Lerp = function (start, end, amount) {
  1251. var r = start.r + ((end.r - start.r) * amount);
  1252. var g = start.g + ((end.g - start.g) * amount);
  1253. var b = start.b + ((end.b - start.b) * amount);
  1254. return new Color3(r, g, b);
  1255. };
  1256. Color3.Red = function () { return new Color3(1, 0, 0); };
  1257. Color3.Green = function () { return new Color3(0, 1, 0); };
  1258. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1259. Color3.Black = function () { return new Color3(0, 0, 0); };
  1260. Color3.White = function () { return new Color3(1, 1, 1); };
  1261. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1262. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1263. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1264. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1265. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1266. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1267. return Color3;
  1268. }());
  1269. BABYLON.Color3 = Color3;
  1270. var Color4 = /** @class */ (function () {
  1271. /**
  1272. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1273. */
  1274. function Color4(r, g, b, a) {
  1275. if (r === void 0) { r = 0; }
  1276. if (g === void 0) { g = 0; }
  1277. if (b === void 0) { b = 0; }
  1278. if (a === void 0) { a = 1; }
  1279. this.r = r;
  1280. this.g = g;
  1281. this.b = b;
  1282. this.a = a;
  1283. }
  1284. // Operators
  1285. /**
  1286. * Adds in place the passed Color4 values to the current Color4.
  1287. * Returns the updated Color4.
  1288. */
  1289. Color4.prototype.addInPlace = function (right) {
  1290. this.r += right.r;
  1291. this.g += right.g;
  1292. this.b += right.b;
  1293. this.a += right.a;
  1294. return this;
  1295. };
  1296. /**
  1297. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1298. */
  1299. Color4.prototype.asArray = function () {
  1300. var result = new Array();
  1301. this.toArray(result, 0);
  1302. return result;
  1303. };
  1304. /**
  1305. * Stores from the starting index in the passed array the Color4 successive values.
  1306. * Returns the Color4.
  1307. */
  1308. Color4.prototype.toArray = function (array, index) {
  1309. if (index === undefined) {
  1310. index = 0;
  1311. }
  1312. array[index] = this.r;
  1313. array[index + 1] = this.g;
  1314. array[index + 2] = this.b;
  1315. array[index + 3] = this.a;
  1316. return this;
  1317. };
  1318. /**
  1319. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1320. */
  1321. Color4.prototype.add = function (right) {
  1322. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1323. };
  1324. /**
  1325. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1326. */
  1327. Color4.prototype.subtract = function (right) {
  1328. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1329. };
  1330. /**
  1331. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1332. * Returns the Color4.
  1333. */
  1334. Color4.prototype.subtractToRef = function (right, result) {
  1335. result.r = this.r - right.r;
  1336. result.g = this.g - right.g;
  1337. result.b = this.b - right.b;
  1338. result.a = this.a - right.a;
  1339. return this;
  1340. };
  1341. /**
  1342. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1343. */
  1344. Color4.prototype.scale = function (scale) {
  1345. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1346. };
  1347. /**
  1348. * Multiplies the current Color4 values by scale and stores the result in "result".
  1349. * Returns the Color4.
  1350. */
  1351. Color4.prototype.scaleToRef = function (scale, result) {
  1352. result.r = this.r * scale;
  1353. result.g = this.g * scale;
  1354. result.b = this.b * scale;
  1355. result.a = this.a * scale;
  1356. return this;
  1357. };
  1358. /**
  1359. * Clamps the rgb values by the min and max values and stores the result into "result".
  1360. * Returns the unmodified current Color4.
  1361. * @param min - minimum clamping value. Defaults to 0
  1362. * @param max - maximum clamping value. Defaults to 1
  1363. * @param result - color to store the result into.
  1364. * @returns - the original Color4
  1365. */
  1366. Color4.prototype.clampToRef = function (min, max, result) {
  1367. if (min === void 0) { min = 0; }
  1368. if (max === void 0) { max = 1; }
  1369. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1370. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1371. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1372. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1373. return this;
  1374. };
  1375. /**
  1376. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1377. * @param color The Color4 (RGBA) value to multiply by
  1378. * @returns A new Color4.
  1379. */
  1380. Color4.prototype.multiply = function (color) {
  1381. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1382. };
  1383. /**
  1384. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1385. * @param color The Color4 (RGBA) value to multiply by
  1386. * @param result The Color4 (RGBA) to fill the result in
  1387. * @returns the result Color4.
  1388. */
  1389. Color4.prototype.multiplyToRef = function (color, result) {
  1390. result.r = this.r * color.r;
  1391. result.g = this.g * color.g;
  1392. result.b = this.b * color.b;
  1393. result.a = this.a * color.a;
  1394. return result;
  1395. };
  1396. /**
  1397. * Returns a string with the Color4 values.
  1398. */
  1399. Color4.prototype.toString = function () {
  1400. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1401. };
  1402. /**
  1403. * Returns the string "Color4"
  1404. */
  1405. Color4.prototype.getClassName = function () {
  1406. return "Color4";
  1407. };
  1408. /**
  1409. * Return the Color4 hash code as a number.
  1410. */
  1411. Color4.prototype.getHashCode = function () {
  1412. var hash = this.r || 0;
  1413. hash = (hash * 397) ^ (this.g || 0);
  1414. hash = (hash * 397) ^ (this.b || 0);
  1415. hash = (hash * 397) ^ (this.a || 0);
  1416. return hash;
  1417. };
  1418. /**
  1419. * Creates a new Color4 copied from the current one.
  1420. */
  1421. Color4.prototype.clone = function () {
  1422. return new Color4(this.r, this.g, this.b, this.a);
  1423. };
  1424. /**
  1425. * Copies the passed Color4 values into the current one.
  1426. * Returns the updated Color4.
  1427. */
  1428. Color4.prototype.copyFrom = function (source) {
  1429. this.r = source.r;
  1430. this.g = source.g;
  1431. this.b = source.b;
  1432. this.a = source.a;
  1433. return this;
  1434. };
  1435. /**
  1436. * Copies the passed float values into the current one.
  1437. * Returns the updated Color4.
  1438. */
  1439. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1440. this.r = r;
  1441. this.g = g;
  1442. this.b = b;
  1443. this.a = a;
  1444. return this;
  1445. };
  1446. /**
  1447. * Copies the passed float values into the current one.
  1448. * Returns the updated Color4.
  1449. */
  1450. Color4.prototype.set = function (r, g, b, a) {
  1451. return this.copyFromFloats(r, g, b, a);
  1452. };
  1453. /**
  1454. * Returns a string containing the hexadecimal Color4 code.
  1455. */
  1456. Color4.prototype.toHexString = function () {
  1457. var intR = (this.r * 255) | 0;
  1458. var intG = (this.g * 255) | 0;
  1459. var intB = (this.b * 255) | 0;
  1460. var intA = (this.a * 255) | 0;
  1461. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1462. };
  1463. /**
  1464. * Returns a new Color4 converted to linear space.
  1465. */
  1466. Color4.prototype.toLinearSpace = function () {
  1467. var convertedColor = new Color4();
  1468. this.toLinearSpaceToRef(convertedColor);
  1469. return convertedColor;
  1470. };
  1471. /**
  1472. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1473. * Returns the unmodified Color4.
  1474. */
  1475. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1476. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1477. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1478. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1479. convertedColor.a = this.a;
  1480. return this;
  1481. };
  1482. /**
  1483. * Returns a new Color4 converted to gamma space.
  1484. */
  1485. Color4.prototype.toGammaSpace = function () {
  1486. var convertedColor = new Color4();
  1487. this.toGammaSpaceToRef(convertedColor);
  1488. return convertedColor;
  1489. };
  1490. /**
  1491. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1492. * Returns the unmodified Color4.
  1493. */
  1494. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1495. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1496. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1497. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1498. convertedColor.a = this.a;
  1499. return this;
  1500. };
  1501. // Statics
  1502. /**
  1503. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1504. */
  1505. Color4.FromHexString = function (hex) {
  1506. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1507. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1508. return new Color4(0.0, 0.0, 0.0, 0.0);
  1509. }
  1510. var r = parseInt(hex.substring(1, 3), 16);
  1511. var g = parseInt(hex.substring(3, 5), 16);
  1512. var b = parseInt(hex.substring(5, 7), 16);
  1513. var a = parseInt(hex.substring(7, 9), 16);
  1514. return Color4.FromInts(r, g, b, a);
  1515. };
  1516. /**
  1517. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1518. */
  1519. Color4.Lerp = function (left, right, amount) {
  1520. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1521. Color4.LerpToRef(left, right, amount, result);
  1522. return result;
  1523. };
  1524. /**
  1525. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1526. */
  1527. Color4.LerpToRef = function (left, right, amount, result) {
  1528. result.r = left.r + (right.r - left.r) * amount;
  1529. result.g = left.g + (right.g - left.g) * amount;
  1530. result.b = left.b + (right.b - left.b) * amount;
  1531. result.a = left.a + (right.a - left.a) * amount;
  1532. };
  1533. /**
  1534. * Creates a new Color4 from the starting index element of the passed array.
  1535. */
  1536. Color4.FromArray = function (array, offset) {
  1537. if (offset === void 0) { offset = 0; }
  1538. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1539. };
  1540. /**
  1541. * Creates a new Color4 from the passed integers ( < 256 ).
  1542. */
  1543. Color4.FromInts = function (r, g, b, a) {
  1544. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1545. };
  1546. Color4.CheckColors4 = function (colors, count) {
  1547. // Check if color3 was used
  1548. if (colors.length === count * 3) {
  1549. var colors4 = [];
  1550. for (var index = 0; index < colors.length; index += 3) {
  1551. var newIndex = (index / 3) * 4;
  1552. colors4[newIndex] = colors[index];
  1553. colors4[newIndex + 1] = colors[index + 1];
  1554. colors4[newIndex + 2] = colors[index + 2];
  1555. colors4[newIndex + 3] = 1.0;
  1556. }
  1557. return colors4;
  1558. }
  1559. return colors;
  1560. };
  1561. return Color4;
  1562. }());
  1563. BABYLON.Color4 = Color4;
  1564. var Vector2 = /** @class */ (function () {
  1565. /**
  1566. * Creates a new Vector2 from the passed x and y coordinates.
  1567. */
  1568. function Vector2(x, y) {
  1569. this.x = x;
  1570. this.y = y;
  1571. }
  1572. /**
  1573. * Returns a string with the Vector2 coordinates.
  1574. */
  1575. Vector2.prototype.toString = function () {
  1576. return "{X: " + this.x + " Y:" + this.y + "}";
  1577. };
  1578. /**
  1579. * Returns the string "Vector2"
  1580. */
  1581. Vector2.prototype.getClassName = function () {
  1582. return "Vector2";
  1583. };
  1584. /**
  1585. * Returns the Vector2 hash code as a number.
  1586. */
  1587. Vector2.prototype.getHashCode = function () {
  1588. var hash = this.x || 0;
  1589. hash = (hash * 397) ^ (this.y || 0);
  1590. return hash;
  1591. };
  1592. // Operators
  1593. /**
  1594. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1595. * Returns the Vector2.
  1596. */
  1597. Vector2.prototype.toArray = function (array, index) {
  1598. if (index === void 0) { index = 0; }
  1599. array[index] = this.x;
  1600. array[index + 1] = this.y;
  1601. return this;
  1602. };
  1603. /**
  1604. * Returns a new array with 2 elements : the Vector2 coordinates.
  1605. */
  1606. Vector2.prototype.asArray = function () {
  1607. var result = new Array();
  1608. this.toArray(result, 0);
  1609. return result;
  1610. };
  1611. /**
  1612. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1613. * Returns the updated Vector2.
  1614. */
  1615. Vector2.prototype.copyFrom = function (source) {
  1616. this.x = source.x;
  1617. this.y = source.y;
  1618. return this;
  1619. };
  1620. /**
  1621. * Sets the Vector2 coordinates with the passed floats.
  1622. * Returns the updated Vector2.
  1623. */
  1624. Vector2.prototype.copyFromFloats = function (x, y) {
  1625. this.x = x;
  1626. this.y = y;
  1627. return this;
  1628. };
  1629. /**
  1630. * Sets the Vector2 coordinates with the passed floats.
  1631. * Returns the updated Vector2.
  1632. */
  1633. Vector2.prototype.set = function (x, y) {
  1634. return this.copyFromFloats(x, y);
  1635. };
  1636. /**
  1637. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1638. */
  1639. Vector2.prototype.add = function (otherVector) {
  1640. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1641. };
  1642. /**
  1643. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1644. * Returns the Vector2.
  1645. */
  1646. Vector2.prototype.addToRef = function (otherVector, result) {
  1647. result.x = this.x + otherVector.x;
  1648. result.y = this.y + otherVector.y;
  1649. return this;
  1650. };
  1651. /**
  1652. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1653. * Returns the updated Vector2.
  1654. */
  1655. Vector2.prototype.addInPlace = function (otherVector) {
  1656. this.x += otherVector.x;
  1657. this.y += otherVector.y;
  1658. return this;
  1659. };
  1660. /**
  1661. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1662. */
  1663. Vector2.prototype.addVector3 = function (otherVector) {
  1664. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1665. };
  1666. /**
  1667. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1668. */
  1669. Vector2.prototype.subtract = function (otherVector) {
  1670. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1671. };
  1672. /**
  1673. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1674. * Returns the Vector2.
  1675. */
  1676. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1677. result.x = this.x - otherVector.x;
  1678. result.y = this.y - otherVector.y;
  1679. return this;
  1680. };
  1681. /**
  1682. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1683. * Returns the updated Vector2.
  1684. */
  1685. Vector2.prototype.subtractInPlace = function (otherVector) {
  1686. this.x -= otherVector.x;
  1687. this.y -= otherVector.y;
  1688. return this;
  1689. };
  1690. /**
  1691. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1692. * Returns the updated Vector2.
  1693. */
  1694. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1695. this.x *= otherVector.x;
  1696. this.y *= otherVector.y;
  1697. return this;
  1698. };
  1699. /**
  1700. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1701. */
  1702. Vector2.prototype.multiply = function (otherVector) {
  1703. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1704. };
  1705. /**
  1706. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1707. * Returns the Vector2.
  1708. */
  1709. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1710. result.x = this.x * otherVector.x;
  1711. result.y = this.y * otherVector.y;
  1712. return this;
  1713. };
  1714. /**
  1715. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1716. */
  1717. Vector2.prototype.multiplyByFloats = function (x, y) {
  1718. return new Vector2(this.x * x, this.y * y);
  1719. };
  1720. /**
  1721. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1722. */
  1723. Vector2.prototype.divide = function (otherVector) {
  1724. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1725. };
  1726. /**
  1727. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1728. * Returns the Vector2.
  1729. */
  1730. Vector2.prototype.divideToRef = function (otherVector, result) {
  1731. result.x = this.x / otherVector.x;
  1732. result.y = this.y / otherVector.y;
  1733. return this;
  1734. };
  1735. /**
  1736. * Divides the current Vector3 coordinates by the passed ones.
  1737. * Returns the updated Vector3.
  1738. */
  1739. Vector2.prototype.divideInPlace = function (otherVector) {
  1740. return this.divideToRef(otherVector, this);
  1741. };
  1742. /**
  1743. * Returns a new Vector2 with current Vector2 negated coordinates.
  1744. */
  1745. Vector2.prototype.negate = function () {
  1746. return new Vector2(-this.x, -this.y);
  1747. };
  1748. /**
  1749. * Multiply the Vector2 coordinates by scale.
  1750. * Returns the updated Vector2.
  1751. */
  1752. Vector2.prototype.scaleInPlace = function (scale) {
  1753. this.x *= scale;
  1754. this.y *= scale;
  1755. return this;
  1756. };
  1757. /**
  1758. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1759. */
  1760. Vector2.prototype.scale = function (scale) {
  1761. return new Vector2(this.x * scale, this.y * scale);
  1762. };
  1763. /**
  1764. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1765. */
  1766. Vector2.prototype.equals = function (otherVector) {
  1767. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1768. };
  1769. /**
  1770. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1771. */
  1772. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1773. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1774. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1775. };
  1776. // Properties
  1777. /**
  1778. * Returns the vector length (float).
  1779. */
  1780. Vector2.prototype.length = function () {
  1781. return Math.sqrt(this.x * this.x + this.y * this.y);
  1782. };
  1783. /**
  1784. * Returns the vector squared length (float);
  1785. */
  1786. Vector2.prototype.lengthSquared = function () {
  1787. return (this.x * this.x + this.y * this.y);
  1788. };
  1789. // Methods
  1790. /**
  1791. * Normalize the vector.
  1792. * Returns the updated Vector2.
  1793. */
  1794. Vector2.prototype.normalize = function () {
  1795. var len = this.length();
  1796. if (len === 0)
  1797. return this;
  1798. var num = 1.0 / len;
  1799. this.x *= num;
  1800. this.y *= num;
  1801. return this;
  1802. };
  1803. /**
  1804. * Returns a new Vector2 copied from the Vector2.
  1805. */
  1806. Vector2.prototype.clone = function () {
  1807. return new Vector2(this.x, this.y);
  1808. };
  1809. // Statics
  1810. /**
  1811. * Returns a new Vector2(0, 0)
  1812. */
  1813. Vector2.Zero = function () {
  1814. return new Vector2(0, 0);
  1815. };
  1816. /**
  1817. * Returns a new Vector2(1, 1)
  1818. */
  1819. Vector2.One = function () {
  1820. return new Vector2(1, 1);
  1821. };
  1822. /**
  1823. * Returns a new Vector2 set from the passed index element of the passed array.
  1824. */
  1825. Vector2.FromArray = function (array, offset) {
  1826. if (offset === void 0) { offset = 0; }
  1827. return new Vector2(array[offset], array[offset + 1]);
  1828. };
  1829. /**
  1830. * Sets "result" from the passed index element of the passed array.
  1831. */
  1832. Vector2.FromArrayToRef = function (array, offset, result) {
  1833. result.x = array[offset];
  1834. result.y = array[offset + 1];
  1835. };
  1836. /**
  1837. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1838. */
  1839. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1840. var squared = amount * amount;
  1841. var cubed = amount * squared;
  1842. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1843. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1844. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1845. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1846. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1847. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1848. return new Vector2(x, y);
  1849. };
  1850. /**
  1851. * 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".
  1852. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1853. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1854. */
  1855. Vector2.Clamp = function (value, min, max) {
  1856. var x = value.x;
  1857. x = (x > max.x) ? max.x : x;
  1858. x = (x < min.x) ? min.x : x;
  1859. var y = value.y;
  1860. y = (y > max.y) ? max.y : y;
  1861. y = (y < min.y) ? min.y : y;
  1862. return new Vector2(x, y);
  1863. };
  1864. /**
  1865. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1866. */
  1867. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1868. var squared = amount * amount;
  1869. var cubed = amount * squared;
  1870. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1871. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1872. var part3 = (cubed - (2.0 * squared)) + amount;
  1873. var part4 = cubed - squared;
  1874. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1875. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1876. return new Vector2(x, y);
  1877. };
  1878. /**
  1879. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1880. */
  1881. Vector2.Lerp = function (start, end, amount) {
  1882. var x = start.x + ((end.x - start.x) * amount);
  1883. var y = start.y + ((end.y - start.y) * amount);
  1884. return new Vector2(x, y);
  1885. };
  1886. /**
  1887. * Returns the dot product (float) of the vector "left" and the vector "right".
  1888. */
  1889. Vector2.Dot = function (left, right) {
  1890. return left.x * right.x + left.y * right.y;
  1891. };
  1892. /**
  1893. * Returns a new Vector2 equal to the normalized passed vector.
  1894. */
  1895. Vector2.Normalize = function (vector) {
  1896. var newVector = vector.clone();
  1897. newVector.normalize();
  1898. return newVector;
  1899. };
  1900. /**
  1901. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1902. */
  1903. Vector2.Minimize = function (left, right) {
  1904. var x = (left.x < right.x) ? left.x : right.x;
  1905. var y = (left.y < right.y) ? left.y : right.y;
  1906. return new Vector2(x, y);
  1907. };
  1908. /**
  1909. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1910. */
  1911. Vector2.Maximize = function (left, right) {
  1912. var x = (left.x > right.x) ? left.x : right.x;
  1913. var y = (left.y > right.y) ? left.y : right.y;
  1914. return new Vector2(x, y);
  1915. };
  1916. /**
  1917. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1918. */
  1919. Vector2.Transform = function (vector, transformation) {
  1920. var r = Vector2.Zero();
  1921. Vector2.TransformToRef(vector, transformation, r);
  1922. return r;
  1923. };
  1924. /**
  1925. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1926. */
  1927. Vector2.TransformToRef = function (vector, transformation, result) {
  1928. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1929. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1930. result.x = x;
  1931. result.y = y;
  1932. };
  1933. /**
  1934. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1935. */
  1936. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1937. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1938. var sign = a < 0 ? -1 : 1;
  1939. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1940. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1941. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1942. };
  1943. /**
  1944. * Returns the distance (float) between the vectors "value1" and "value2".
  1945. */
  1946. Vector2.Distance = function (value1, value2) {
  1947. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1948. };
  1949. /**
  1950. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1951. */
  1952. Vector2.DistanceSquared = function (value1, value2) {
  1953. var x = value1.x - value2.x;
  1954. var y = value1.y - value2.y;
  1955. return (x * x) + (y * y);
  1956. };
  1957. /**
  1958. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1959. */
  1960. Vector2.Center = function (value1, value2) {
  1961. var center = value1.add(value2);
  1962. center.scaleInPlace(0.5);
  1963. return center;
  1964. };
  1965. /**
  1966. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1967. */
  1968. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1969. var l2 = Vector2.DistanceSquared(segA, segB);
  1970. if (l2 === 0.0) {
  1971. return Vector2.Distance(p, segA);
  1972. }
  1973. var v = segB.subtract(segA);
  1974. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1975. var proj = segA.add(v.multiplyByFloats(t, t));
  1976. return Vector2.Distance(p, proj);
  1977. };
  1978. return Vector2;
  1979. }());
  1980. BABYLON.Vector2 = Vector2;
  1981. var Vector3 = /** @class */ (function () {
  1982. /**
  1983. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1984. * A Vector3 is the main object used in 3D geometry.
  1985. * It can represent etiher the coordinates of a point the space, either a direction.
  1986. */
  1987. function Vector3(x, y, z) {
  1988. this.x = x;
  1989. this.y = y;
  1990. this.z = z;
  1991. }
  1992. /**
  1993. * Returns a string with the Vector3 coordinates.
  1994. */
  1995. Vector3.prototype.toString = function () {
  1996. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1997. };
  1998. /**
  1999. * Returns the string "Vector3"
  2000. */
  2001. Vector3.prototype.getClassName = function () {
  2002. return "Vector3";
  2003. };
  2004. /**
  2005. * Returns the Vector hash code.
  2006. */
  2007. Vector3.prototype.getHashCode = function () {
  2008. var hash = this.x || 0;
  2009. hash = (hash * 397) ^ (this.y || 0);
  2010. hash = (hash * 397) ^ (this.z || 0);
  2011. return hash;
  2012. };
  2013. // Operators
  2014. /**
  2015. * Returns a new array with three elements : the coordinates the Vector3.
  2016. */
  2017. Vector3.prototype.asArray = function () {
  2018. var result = [];
  2019. this.toArray(result, 0);
  2020. return result;
  2021. };
  2022. /**
  2023. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2024. * Returns the Vector3.
  2025. */
  2026. Vector3.prototype.toArray = function (array, index) {
  2027. if (index === void 0) { index = 0; }
  2028. array[index] = this.x;
  2029. array[index + 1] = this.y;
  2030. array[index + 2] = this.z;
  2031. return this;
  2032. };
  2033. /**
  2034. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2035. */
  2036. Vector3.prototype.toQuaternion = function () {
  2037. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2038. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2039. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2040. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2041. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2042. var cosy = Math.cos(this.y * 0.5);
  2043. var siny = Math.sin(this.y * 0.5);
  2044. result.x = coszMinusx * siny;
  2045. result.y = -sinzMinusx * siny;
  2046. result.z = sinxPlusz * cosy;
  2047. result.w = cosxPlusz * cosy;
  2048. return result;
  2049. };
  2050. /**
  2051. * Adds the passed vector to the current Vector3.
  2052. * Returns the updated Vector3.
  2053. */
  2054. Vector3.prototype.addInPlace = function (otherVector) {
  2055. this.x += otherVector.x;
  2056. this.y += otherVector.y;
  2057. this.z += otherVector.z;
  2058. return this;
  2059. };
  2060. /**
  2061. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2062. */
  2063. Vector3.prototype.add = function (otherVector) {
  2064. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2065. };
  2066. /**
  2067. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2068. * Returns the current Vector3.
  2069. */
  2070. Vector3.prototype.addToRef = function (otherVector, result) {
  2071. result.x = this.x + otherVector.x;
  2072. result.y = this.y + otherVector.y;
  2073. result.z = this.z + otherVector.z;
  2074. return this;
  2075. };
  2076. /**
  2077. * Subtract the passed vector from the current Vector3.
  2078. * Returns the updated Vector3.
  2079. */
  2080. Vector3.prototype.subtractInPlace = function (otherVector) {
  2081. this.x -= otherVector.x;
  2082. this.y -= otherVector.y;
  2083. this.z -= otherVector.z;
  2084. return this;
  2085. };
  2086. /**
  2087. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2088. */
  2089. Vector3.prototype.subtract = function (otherVector) {
  2090. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2091. };
  2092. /**
  2093. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2094. * Returns the current Vector3.
  2095. */
  2096. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2097. result.x = this.x - otherVector.x;
  2098. result.y = this.y - otherVector.y;
  2099. result.z = this.z - otherVector.z;
  2100. return this;
  2101. };
  2102. /**
  2103. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2104. */
  2105. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2106. return new Vector3(this.x - x, this.y - y, this.z - z);
  2107. };
  2108. /**
  2109. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2110. * Returns the current Vector3.
  2111. */
  2112. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2113. result.x = this.x - x;
  2114. result.y = this.y - y;
  2115. result.z = this.z - z;
  2116. return this;
  2117. };
  2118. /**
  2119. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2120. */
  2121. Vector3.prototype.negate = function () {
  2122. return new Vector3(-this.x, -this.y, -this.z);
  2123. };
  2124. /**
  2125. * Multiplies the Vector3 coordinates by the float "scale".
  2126. * Returns the updated Vector3.
  2127. */
  2128. Vector3.prototype.scaleInPlace = function (scale) {
  2129. this.x *= scale;
  2130. this.y *= scale;
  2131. this.z *= scale;
  2132. return this;
  2133. };
  2134. /**
  2135. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2136. */
  2137. Vector3.prototype.scale = function (scale) {
  2138. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2139. };
  2140. /**
  2141. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2142. * Returns the current Vector3.
  2143. */
  2144. Vector3.prototype.scaleToRef = function (scale, result) {
  2145. result.x = this.x * scale;
  2146. result.y = this.y * scale;
  2147. result.z = this.z * scale;
  2148. return this;
  2149. };
  2150. /**
  2151. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2152. */
  2153. Vector3.prototype.equals = function (otherVector) {
  2154. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2155. };
  2156. /**
  2157. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2158. */
  2159. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2160. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2161. 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);
  2162. };
  2163. /**
  2164. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2165. */
  2166. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2167. return this.x === x && this.y === y && this.z === z;
  2168. };
  2169. /**
  2170. * Muliplies the current Vector3 coordinates by the passed ones.
  2171. * Returns the updated Vector3.
  2172. */
  2173. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2174. this.x *= otherVector.x;
  2175. this.y *= otherVector.y;
  2176. this.z *= otherVector.z;
  2177. return this;
  2178. };
  2179. /**
  2180. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2181. */
  2182. Vector3.prototype.multiply = function (otherVector) {
  2183. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2184. };
  2185. /**
  2186. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2187. * Returns the current Vector3.
  2188. */
  2189. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2190. result.x = this.x * otherVector.x;
  2191. result.y = this.y * otherVector.y;
  2192. result.z = this.z * otherVector.z;
  2193. return this;
  2194. };
  2195. /**
  2196. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2197. */
  2198. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2199. return new Vector3(this.x * x, this.y * y, this.z * z);
  2200. };
  2201. /**
  2202. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2203. */
  2204. Vector3.prototype.divide = function (otherVector) {
  2205. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2206. };
  2207. /**
  2208. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2209. * Returns the current Vector3.
  2210. */
  2211. Vector3.prototype.divideToRef = function (otherVector, result) {
  2212. result.x = this.x / otherVector.x;
  2213. result.y = this.y / otherVector.y;
  2214. result.z = this.z / otherVector.z;
  2215. return this;
  2216. };
  2217. /**
  2218. * Divides the current Vector3 coordinates by the passed ones.
  2219. * Returns the updated Vector3.
  2220. */
  2221. Vector3.prototype.divideInPlace = function (otherVector) {
  2222. return this.divideToRef(otherVector, this);
  2223. };
  2224. /**
  2225. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2226. * Returns the updated Vector3.
  2227. */
  2228. Vector3.prototype.MinimizeInPlace = function (other) {
  2229. if (other.x < this.x)
  2230. this.x = other.x;
  2231. if (other.y < this.y)
  2232. this.y = other.y;
  2233. if (other.z < this.z)
  2234. this.z = other.z;
  2235. return this;
  2236. };
  2237. /**
  2238. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2239. * Returns the updated Vector3.
  2240. */
  2241. Vector3.prototype.MaximizeInPlace = function (other) {
  2242. if (other.x > this.x)
  2243. this.x = other.x;
  2244. if (other.y > this.y)
  2245. this.y = other.y;
  2246. if (other.z > this.z)
  2247. this.z = other.z;
  2248. return this;
  2249. };
  2250. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2251. /**
  2252. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2253. */
  2254. get: function () {
  2255. var absX = Math.abs(this.x);
  2256. var absY = Math.abs(this.y);
  2257. if (absX !== absY) {
  2258. return true;
  2259. }
  2260. var absZ = Math.abs(this.z);
  2261. if (absX !== absZ) {
  2262. return true;
  2263. }
  2264. if (absY !== absZ) {
  2265. return true;
  2266. }
  2267. return false;
  2268. },
  2269. enumerable: true,
  2270. configurable: true
  2271. });
  2272. // Properties
  2273. /**
  2274. * Returns the length of the Vector3 (float).
  2275. */
  2276. Vector3.prototype.length = function () {
  2277. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2278. };
  2279. /**
  2280. * Returns the squared length of the Vector3 (float).
  2281. */
  2282. Vector3.prototype.lengthSquared = function () {
  2283. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2284. };
  2285. /**
  2286. * Normalize the current Vector3.
  2287. * Returns the updated Vector3.
  2288. * /!\ In place operation.
  2289. */
  2290. Vector3.prototype.normalize = function () {
  2291. var len = this.length();
  2292. if (len === 0 || len === 1.0)
  2293. return this;
  2294. var num = 1.0 / len;
  2295. this.x *= num;
  2296. this.y *= num;
  2297. this.z *= num;
  2298. return this;
  2299. };
  2300. /**
  2301. * Normalize the current Vector3 to a new vector.
  2302. * @returns the new Vector3.
  2303. */
  2304. Vector3.prototype.normalizeToNew = function () {
  2305. var normalized = new Vector3(0, 0, 0);
  2306. this.normalizeToRef(normalized);
  2307. return normalized;
  2308. };
  2309. /**
  2310. * Normalize the current Vector3 to the reference.
  2311. * @param the reference to update.
  2312. * @returns the updated Vector3.
  2313. */
  2314. Vector3.prototype.normalizeToRef = function (reference) {
  2315. var len = this.length();
  2316. if (len === 0 || len === 1.0) {
  2317. reference.set(this.x, this.y, this.z);
  2318. return reference;
  2319. }
  2320. var scale = 1.0 / len;
  2321. this.scaleToRef(scale, reference);
  2322. return reference;
  2323. };
  2324. /**
  2325. * Returns a new Vector3 copied from the current Vector3.
  2326. */
  2327. Vector3.prototype.clone = function () {
  2328. return new Vector3(this.x, this.y, this.z);
  2329. };
  2330. /**
  2331. * Copies the passed vector coordinates to the current Vector3 ones.
  2332. * Returns the updated Vector3.
  2333. */
  2334. Vector3.prototype.copyFrom = function (source) {
  2335. this.x = source.x;
  2336. this.y = source.y;
  2337. this.z = source.z;
  2338. return this;
  2339. };
  2340. /**
  2341. * Copies the passed floats to the current Vector3 coordinates.
  2342. * Returns the updated Vector3.
  2343. */
  2344. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2345. this.x = x;
  2346. this.y = y;
  2347. this.z = z;
  2348. return this;
  2349. };
  2350. /**
  2351. * Copies the passed floats to the current Vector3 coordinates.
  2352. * Returns the updated Vector3.
  2353. */
  2354. Vector3.prototype.set = function (x, y, z) {
  2355. return this.copyFromFloats(x, y, z);
  2356. };
  2357. // Statics
  2358. /**
  2359. *
  2360. */
  2361. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2362. var d0 = Vector3.Dot(vector0, axis) - size;
  2363. var d1 = Vector3.Dot(vector1, axis) - size;
  2364. var s = d0 / (d0 - d1);
  2365. return s;
  2366. };
  2367. /**
  2368. * Get angle between two vectors.
  2369. * @param vector0 angle between vector0 and vector1
  2370. * @param vector1 angle between vector0 and vector1
  2371. * @param normal direction of the normal.
  2372. * @return the angle between vector0 and vector1.
  2373. */
  2374. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2375. var v0 = vector0.clone().normalize();
  2376. var v1 = vector1.clone().normalize();
  2377. var dot = Vector3.Dot(v0, v1);
  2378. var n = Vector3.Cross(v0, v1);
  2379. if (Vector3.Dot(n, normal) > 0) {
  2380. return Math.acos(dot);
  2381. }
  2382. return -Math.acos(dot);
  2383. };
  2384. /**
  2385. * Returns a new Vector3 set from the index "offset" of the passed array.
  2386. */
  2387. Vector3.FromArray = function (array, offset) {
  2388. if (!offset) {
  2389. offset = 0;
  2390. }
  2391. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2392. };
  2393. /**
  2394. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2395. * This function is deprecated. Use FromArray instead.
  2396. */
  2397. Vector3.FromFloatArray = function (array, offset) {
  2398. return Vector3.FromArray(array, offset);
  2399. };
  2400. /**
  2401. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2402. */
  2403. Vector3.FromArrayToRef = function (array, offset, result) {
  2404. result.x = array[offset];
  2405. result.y = array[offset + 1];
  2406. result.z = array[offset + 2];
  2407. };
  2408. /**
  2409. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2410. * This function is deprecated. Use FromArrayToRef instead.
  2411. */
  2412. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2413. return Vector3.FromArrayToRef(array, offset, result);
  2414. };
  2415. /**
  2416. * Sets the passed vector "result" with the passed floats.
  2417. */
  2418. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2419. result.x = x;
  2420. result.y = y;
  2421. result.z = z;
  2422. };
  2423. /**
  2424. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2425. */
  2426. Vector3.Zero = function () {
  2427. return new Vector3(0.0, 0.0, 0.0);
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2431. */
  2432. Vector3.One = function () {
  2433. return new Vector3(1.0, 1.0, 1.0);
  2434. };
  2435. /**
  2436. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2437. */
  2438. Vector3.Up = function () {
  2439. return new Vector3(0.0, 1.0, 0.0);
  2440. };
  2441. /**
  2442. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2443. */
  2444. Vector3.Forward = function () {
  2445. return new Vector3(0.0, 0.0, 1.0);
  2446. };
  2447. /**
  2448. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2449. */
  2450. Vector3.Right = function () {
  2451. return new Vector3(1.0, 0.0, 0.0);
  2452. };
  2453. /**
  2454. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2455. */
  2456. Vector3.Left = function () {
  2457. return new Vector3(-1.0, 0.0, 0.0);
  2458. };
  2459. /**
  2460. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2461. * This method computes tranformed coordinates only, not transformed direction vectors.
  2462. */
  2463. Vector3.TransformCoordinates = function (vector, transformation) {
  2464. var result = Vector3.Zero();
  2465. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2466. return result;
  2467. };
  2468. /**
  2469. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2470. * This method computes tranformed coordinates only, not transformed direction vectors.
  2471. */
  2472. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2473. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2474. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2475. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2476. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2477. result.x = x / w;
  2478. result.y = y / w;
  2479. result.z = z / w;
  2480. };
  2481. /**
  2482. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2483. * This method computes tranformed coordinates only, not transformed direction vectors.
  2484. */
  2485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2490. result.x = rx / rw;
  2491. result.y = ry / rw;
  2492. result.z = rz / rw;
  2493. };
  2494. /**
  2495. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2496. * This methods computes transformed normalized direction vectors only.
  2497. */
  2498. Vector3.TransformNormal = function (vector, transformation) {
  2499. var result = Vector3.Zero();
  2500. Vector3.TransformNormalToRef(vector, transformation, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2505. * This methods computes transformed normalized direction vectors only.
  2506. */
  2507. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2508. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2509. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2510. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2511. result.x = x;
  2512. result.y = y;
  2513. result.z = z;
  2514. };
  2515. /**
  2516. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2517. * This methods computes transformed normalized direction vectors only.
  2518. */
  2519. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2520. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2521. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2522. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2523. };
  2524. /**
  2525. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2526. */
  2527. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2528. var squared = amount * amount;
  2529. var cubed = amount * squared;
  2530. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2531. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2532. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2533. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2534. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2535. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2536. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2537. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2538. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2539. return new Vector3(x, y, z);
  2540. };
  2541. /**
  2542. * 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".
  2543. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2544. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2545. */
  2546. Vector3.Clamp = function (value, min, max) {
  2547. var x = value.x;
  2548. x = (x > max.x) ? max.x : x;
  2549. x = (x < min.x) ? min.x : x;
  2550. var y = value.y;
  2551. y = (y > max.y) ? max.y : y;
  2552. y = (y < min.y) ? min.y : y;
  2553. var z = value.z;
  2554. z = (z > max.z) ? max.z : z;
  2555. z = (z < min.z) ? min.z : z;
  2556. return new Vector3(x, y, z);
  2557. };
  2558. /**
  2559. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2560. */
  2561. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2562. var squared = amount * amount;
  2563. var cubed = amount * squared;
  2564. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2565. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2566. var part3 = (cubed - (2.0 * squared)) + amount;
  2567. var part4 = cubed - squared;
  2568. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2569. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2570. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2571. return new Vector3(x, y, z);
  2572. };
  2573. /**
  2574. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2575. */
  2576. Vector3.Lerp = function (start, end, amount) {
  2577. var result = new Vector3(0, 0, 0);
  2578. Vector3.LerpToRef(start, end, amount, result);
  2579. return result;
  2580. };
  2581. /**
  2582. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2583. */
  2584. Vector3.LerpToRef = function (start, end, amount, result) {
  2585. result.x = start.x + ((end.x - start.x) * amount);
  2586. result.y = start.y + ((end.y - start.y) * amount);
  2587. result.z = start.z + ((end.z - start.z) * amount);
  2588. };
  2589. /**
  2590. * Returns the dot product (float) between the vectors "left" and "right".
  2591. */
  2592. Vector3.Dot = function (left, right) {
  2593. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2594. };
  2595. /**
  2596. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2597. * The cross product is then orthogonal to both "left" and "right".
  2598. */
  2599. Vector3.Cross = function (left, right) {
  2600. var result = Vector3.Zero();
  2601. Vector3.CrossToRef(left, right, result);
  2602. return result;
  2603. };
  2604. /**
  2605. * Sets the passed vector "result" with the cross product of "left" and "right".
  2606. * The cross product is then orthogonal to both "left" and "right".
  2607. */
  2608. Vector3.CrossToRef = function (left, right, result) {
  2609. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2610. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2611. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2612. result.copyFrom(MathTmp.Vector3[0]);
  2613. };
  2614. /**
  2615. * Returns a new Vector3 as the normalization of the passed vector.
  2616. */
  2617. Vector3.Normalize = function (vector) {
  2618. var result = Vector3.Zero();
  2619. Vector3.NormalizeToRef(vector, result);
  2620. return result;
  2621. };
  2622. /**
  2623. * Sets the passed vector "result" with the normalization of the passed first vector.
  2624. */
  2625. Vector3.NormalizeToRef = function (vector, result) {
  2626. result.copyFrom(vector);
  2627. result.normalize();
  2628. };
  2629. Vector3.Project = function (vector, world, transform, viewport) {
  2630. var cw = viewport.width;
  2631. var ch = viewport.height;
  2632. var cx = viewport.x;
  2633. var cy = viewport.y;
  2634. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2635. 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);
  2636. var matrix = MathTmp.Matrix[0];
  2637. world.multiplyToRef(transform, matrix);
  2638. matrix.multiplyToRef(viewportMatrix, matrix);
  2639. return Vector3.TransformCoordinates(vector, matrix);
  2640. };
  2641. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2642. var matrix = MathTmp.Matrix[0];
  2643. world.multiplyToRef(transform, matrix);
  2644. matrix.invert();
  2645. source.x = source.x / viewportWidth * 2 - 1;
  2646. source.y = -(source.y / viewportHeight * 2 - 1);
  2647. var vector = Vector3.TransformCoordinates(source, matrix);
  2648. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2649. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2650. vector = vector.scale(1.0 / num);
  2651. }
  2652. return vector;
  2653. };
  2654. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2655. var result = Vector3.Zero();
  2656. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2657. return result;
  2658. };
  2659. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2660. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2661. };
  2662. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2663. var matrix = MathTmp.Matrix[0];
  2664. world.multiplyToRef(view, matrix);
  2665. matrix.multiplyToRef(projection, matrix);
  2666. matrix.invert();
  2667. var screenSource = MathTmp.Vector3[0];
  2668. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2669. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2670. screenSource.z = 2 * sourceZ - 1.0;
  2671. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2672. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2673. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2674. result.scaleInPlace(1.0 / num);
  2675. }
  2676. };
  2677. Vector3.Minimize = function (left, right) {
  2678. var min = left.clone();
  2679. min.MinimizeInPlace(right);
  2680. return min;
  2681. };
  2682. Vector3.Maximize = function (left, right) {
  2683. var max = left.clone();
  2684. max.MaximizeInPlace(right);
  2685. return max;
  2686. };
  2687. /**
  2688. * Returns the distance (float) between the vectors "value1" and "value2".
  2689. */
  2690. Vector3.Distance = function (value1, value2) {
  2691. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2692. };
  2693. /**
  2694. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2695. */
  2696. Vector3.DistanceSquared = function (value1, value2) {
  2697. var x = value1.x - value2.x;
  2698. var y = value1.y - value2.y;
  2699. var z = value1.z - value2.z;
  2700. return (x * x) + (y * y) + (z * z);
  2701. };
  2702. /**
  2703. * Returns a new Vector3 located at the center between "value1" and "value2".
  2704. */
  2705. Vector3.Center = function (value1, value2) {
  2706. var center = value1.add(value2);
  2707. center.scaleInPlace(0.5);
  2708. return center;
  2709. };
  2710. /**
  2711. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2712. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2713. * to something in order to rotate it from its local system to the given target system.
  2714. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2715. * Returns a new Vector3.
  2716. */
  2717. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2718. var rotation = Vector3.Zero();
  2719. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2720. return rotation;
  2721. };
  2722. /**
  2723. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2724. */
  2725. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2726. var quat = MathTmp.Quaternion[0];
  2727. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2728. quat.toEulerAnglesToRef(ref);
  2729. };
  2730. return Vector3;
  2731. }());
  2732. BABYLON.Vector3 = Vector3;
  2733. //Vector4 class created for EulerAngle class conversion to Quaternion
  2734. var Vector4 = /** @class */ (function () {
  2735. /**
  2736. * Creates a Vector4 object from the passed floats.
  2737. */
  2738. function Vector4(x, y, z, w) {
  2739. this.x = x;
  2740. this.y = y;
  2741. this.z = z;
  2742. this.w = w;
  2743. }
  2744. /**
  2745. * Returns the string with the Vector4 coordinates.
  2746. */
  2747. Vector4.prototype.toString = function () {
  2748. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2749. };
  2750. /**
  2751. * Returns the string "Vector4".
  2752. */
  2753. Vector4.prototype.getClassName = function () {
  2754. return "Vector4";
  2755. };
  2756. /**
  2757. * Returns the Vector4 hash code.
  2758. */
  2759. Vector4.prototype.getHashCode = function () {
  2760. var hash = this.x || 0;
  2761. hash = (hash * 397) ^ (this.y || 0);
  2762. hash = (hash * 397) ^ (this.z || 0);
  2763. hash = (hash * 397) ^ (this.w || 0);
  2764. return hash;
  2765. };
  2766. // Operators
  2767. /**
  2768. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2769. */
  2770. Vector4.prototype.asArray = function () {
  2771. var result = new Array();
  2772. this.toArray(result, 0);
  2773. return result;
  2774. };
  2775. /**
  2776. * Populates the passed array from the passed index with the Vector4 coordinates.
  2777. * Returns the Vector4.
  2778. */
  2779. Vector4.prototype.toArray = function (array, index) {
  2780. if (index === undefined) {
  2781. index = 0;
  2782. }
  2783. array[index] = this.x;
  2784. array[index + 1] = this.y;
  2785. array[index + 2] = this.z;
  2786. array[index + 3] = this.w;
  2787. return this;
  2788. };
  2789. /**
  2790. * Adds the passed vector to the current Vector4.
  2791. * Returns the updated Vector4.
  2792. */
  2793. Vector4.prototype.addInPlace = function (otherVector) {
  2794. this.x += otherVector.x;
  2795. this.y += otherVector.y;
  2796. this.z += otherVector.z;
  2797. this.w += otherVector.w;
  2798. return this;
  2799. };
  2800. /**
  2801. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2802. */
  2803. Vector4.prototype.add = function (otherVector) {
  2804. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2805. };
  2806. /**
  2807. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2808. * Returns the current Vector4.
  2809. */
  2810. Vector4.prototype.addToRef = function (otherVector, result) {
  2811. result.x = this.x + otherVector.x;
  2812. result.y = this.y + otherVector.y;
  2813. result.z = this.z + otherVector.z;
  2814. result.w = this.w + otherVector.w;
  2815. return this;
  2816. };
  2817. /**
  2818. * Subtract in place the passed vector from the current Vector4.
  2819. * Returns the updated Vector4.
  2820. */
  2821. Vector4.prototype.subtractInPlace = function (otherVector) {
  2822. this.x -= otherVector.x;
  2823. this.y -= otherVector.y;
  2824. this.z -= otherVector.z;
  2825. this.w -= otherVector.w;
  2826. return this;
  2827. };
  2828. /**
  2829. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2830. */
  2831. Vector4.prototype.subtract = function (otherVector) {
  2832. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2833. };
  2834. /**
  2835. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2836. * Returns the current Vector4.
  2837. */
  2838. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2839. result.x = this.x - otherVector.x;
  2840. result.y = this.y - otherVector.y;
  2841. result.z = this.z - otherVector.z;
  2842. result.w = this.w - otherVector.w;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2847. */
  2848. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2849. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2850. };
  2851. /**
  2852. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2853. * Returns the current Vector4.
  2854. */
  2855. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2856. result.x = this.x - x;
  2857. result.y = this.y - y;
  2858. result.z = this.z - z;
  2859. result.w = this.w - w;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2864. */
  2865. Vector4.prototype.negate = function () {
  2866. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2867. };
  2868. /**
  2869. * Multiplies the current Vector4 coordinates by scale (float).
  2870. * Returns the updated Vector4.
  2871. */
  2872. Vector4.prototype.scaleInPlace = function (scale) {
  2873. this.x *= scale;
  2874. this.y *= scale;
  2875. this.z *= scale;
  2876. this.w *= scale;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2881. */
  2882. Vector4.prototype.scale = function (scale) {
  2883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2884. };
  2885. /**
  2886. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2887. * Returns the current Vector4.
  2888. */
  2889. Vector4.prototype.scaleToRef = function (scale, result) {
  2890. result.x = this.x * scale;
  2891. result.y = this.y * scale;
  2892. result.z = this.z * scale;
  2893. result.w = this.w * scale;
  2894. return this;
  2895. };
  2896. /**
  2897. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2898. */
  2899. Vector4.prototype.equals = function (otherVector) {
  2900. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2901. };
  2902. /**
  2903. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2904. */
  2905. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2906. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2907. return otherVector
  2908. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2909. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2910. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2911. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2912. };
  2913. /**
  2914. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2915. */
  2916. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2917. return this.x === x && this.y === y && this.z === z && this.w === w;
  2918. };
  2919. /**
  2920. * Multiplies in place the current Vector4 by the passed one.
  2921. * Returns the updated Vector4.
  2922. */
  2923. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2924. this.x *= otherVector.x;
  2925. this.y *= otherVector.y;
  2926. this.z *= otherVector.z;
  2927. this.w *= otherVector.w;
  2928. return this;
  2929. };
  2930. /**
  2931. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2932. */
  2933. Vector4.prototype.multiply = function (otherVector) {
  2934. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2935. };
  2936. /**
  2937. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2938. * Returns the current Vector4.
  2939. */
  2940. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2941. result.x = this.x * otherVector.x;
  2942. result.y = this.y * otherVector.y;
  2943. result.z = this.z * otherVector.z;
  2944. result.w = this.w * otherVector.w;
  2945. return this;
  2946. };
  2947. /**
  2948. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2949. */
  2950. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2951. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2952. };
  2953. /**
  2954. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2955. */
  2956. Vector4.prototype.divide = function (otherVector) {
  2957. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2958. };
  2959. /**
  2960. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2961. * Returns the current Vector4.
  2962. */
  2963. Vector4.prototype.divideToRef = function (otherVector, result) {
  2964. result.x = this.x / otherVector.x;
  2965. result.y = this.y / otherVector.y;
  2966. result.z = this.z / otherVector.z;
  2967. result.w = this.w / otherVector.w;
  2968. return this;
  2969. };
  2970. /**
  2971. * Divides the current Vector3 coordinates by the passed ones.
  2972. * Returns the updated Vector3.
  2973. */
  2974. Vector4.prototype.divideInPlace = function (otherVector) {
  2975. return this.divideToRef(otherVector, this);
  2976. };
  2977. /**
  2978. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2979. */
  2980. Vector4.prototype.MinimizeInPlace = function (other) {
  2981. if (other.x < this.x)
  2982. this.x = other.x;
  2983. if (other.y < this.y)
  2984. this.y = other.y;
  2985. if (other.z < this.z)
  2986. this.z = other.z;
  2987. if (other.w < this.w)
  2988. this.w = other.w;
  2989. return this;
  2990. };
  2991. /**
  2992. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2993. */
  2994. Vector4.prototype.MaximizeInPlace = function (other) {
  2995. if (other.x > this.x)
  2996. this.x = other.x;
  2997. if (other.y > this.y)
  2998. this.y = other.y;
  2999. if (other.z > this.z)
  3000. this.z = other.z;
  3001. if (other.w > this.w)
  3002. this.w = other.w;
  3003. return this;
  3004. };
  3005. // Properties
  3006. /**
  3007. * Returns the Vector4 length (float).
  3008. */
  3009. Vector4.prototype.length = function () {
  3010. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3011. };
  3012. /**
  3013. * Returns the Vector4 squared length (float).
  3014. */
  3015. Vector4.prototype.lengthSquared = function () {
  3016. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3017. };
  3018. // Methods
  3019. /**
  3020. * Normalizes in place the Vector4.
  3021. * Returns the updated Vector4.
  3022. */
  3023. Vector4.prototype.normalize = function () {
  3024. var len = this.length();
  3025. if (len === 0)
  3026. return this;
  3027. var num = 1.0 / len;
  3028. this.x *= num;
  3029. this.y *= num;
  3030. this.z *= num;
  3031. this.w *= num;
  3032. return this;
  3033. };
  3034. /**
  3035. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3036. */
  3037. Vector4.prototype.toVector3 = function () {
  3038. return new Vector3(this.x, this.y, this.z);
  3039. };
  3040. /**
  3041. * Returns a new Vector4 copied from the current one.
  3042. */
  3043. Vector4.prototype.clone = function () {
  3044. return new Vector4(this.x, this.y, this.z, this.w);
  3045. };
  3046. /**
  3047. * Updates the current Vector4 with the passed one coordinates.
  3048. * Returns the updated Vector4.
  3049. */
  3050. Vector4.prototype.copyFrom = function (source) {
  3051. this.x = source.x;
  3052. this.y = source.y;
  3053. this.z = source.z;
  3054. this.w = source.w;
  3055. return this;
  3056. };
  3057. /**
  3058. * Updates the current Vector4 coordinates with the passed floats.
  3059. * Returns the updated Vector4.
  3060. */
  3061. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3062. this.x = x;
  3063. this.y = y;
  3064. this.z = z;
  3065. this.w = w;
  3066. return this;
  3067. };
  3068. /**
  3069. * Updates the current Vector4 coordinates with the passed floats.
  3070. * Returns the updated Vector4.
  3071. */
  3072. Vector4.prototype.set = function (x, y, z, w) {
  3073. return this.copyFromFloats(x, y, z, w);
  3074. };
  3075. // Statics
  3076. /**
  3077. * Returns a new Vector4 set from the starting index of the passed array.
  3078. */
  3079. Vector4.FromArray = function (array, offset) {
  3080. if (!offset) {
  3081. offset = 0;
  3082. }
  3083. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3084. };
  3085. /**
  3086. * Updates the passed vector "result" from the starting index of the passed array.
  3087. */
  3088. Vector4.FromArrayToRef = function (array, offset, result) {
  3089. result.x = array[offset];
  3090. result.y = array[offset + 1];
  3091. result.z = array[offset + 2];
  3092. result.w = array[offset + 3];
  3093. };
  3094. /**
  3095. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3096. */
  3097. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3098. Vector4.FromArrayToRef(array, offset, result);
  3099. };
  3100. /**
  3101. * Updates the passed vector "result" coordinates from the passed floats.
  3102. */
  3103. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3104. result.x = x;
  3105. result.y = y;
  3106. result.z = z;
  3107. result.w = w;
  3108. };
  3109. /**
  3110. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3111. */
  3112. Vector4.Zero = function () {
  3113. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3117. */
  3118. Vector4.One = function () {
  3119. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3120. };
  3121. /**
  3122. * Returns a new normalized Vector4 from the passed one.
  3123. */
  3124. Vector4.Normalize = function (vector) {
  3125. var result = Vector4.Zero();
  3126. Vector4.NormalizeToRef(vector, result);
  3127. return result;
  3128. };
  3129. /**
  3130. * Updates the passed vector "result" from the normalization of the passed one.
  3131. */
  3132. Vector4.NormalizeToRef = function (vector, result) {
  3133. result.copyFrom(vector);
  3134. result.normalize();
  3135. };
  3136. Vector4.Minimize = function (left, right) {
  3137. var min = left.clone();
  3138. min.MinimizeInPlace(right);
  3139. return min;
  3140. };
  3141. Vector4.Maximize = function (left, right) {
  3142. var max = left.clone();
  3143. max.MaximizeInPlace(right);
  3144. return max;
  3145. };
  3146. /**
  3147. * Returns the distance (float) between the vectors "value1" and "value2".
  3148. */
  3149. Vector4.Distance = function (value1, value2) {
  3150. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3151. };
  3152. /**
  3153. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3154. */
  3155. Vector4.DistanceSquared = function (value1, value2) {
  3156. var x = value1.x - value2.x;
  3157. var y = value1.y - value2.y;
  3158. var z = value1.z - value2.z;
  3159. var w = value1.w - value2.w;
  3160. return (x * x) + (y * y) + (z * z) + (w * w);
  3161. };
  3162. /**
  3163. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3164. */
  3165. Vector4.Center = function (value1, value2) {
  3166. var center = value1.add(value2);
  3167. center.scaleInPlace(0.5);
  3168. return center;
  3169. };
  3170. /**
  3171. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3172. * This methods computes transformed normalized direction vectors only.
  3173. */
  3174. Vector4.TransformNormal = function (vector, transformation) {
  3175. var result = Vector4.Zero();
  3176. Vector4.TransformNormalToRef(vector, transformation, result);
  3177. return result;
  3178. };
  3179. /**
  3180. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3181. * This methods computes transformed normalized direction vectors only.
  3182. */
  3183. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3184. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3185. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3186. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3187. result.x = x;
  3188. result.y = y;
  3189. result.z = z;
  3190. result.w = vector.w;
  3191. };
  3192. /**
  3193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3194. * This methods computes transformed normalized direction vectors only.
  3195. */
  3196. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3197. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3198. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3199. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3200. result.w = w;
  3201. };
  3202. return Vector4;
  3203. }());
  3204. BABYLON.Vector4 = Vector4;
  3205. var Size = /** @class */ (function () {
  3206. /**
  3207. * Creates a Size object from the passed width and height (floats).
  3208. */
  3209. function Size(width, height) {
  3210. this.width = width;
  3211. this.height = height;
  3212. }
  3213. // Returns a string with the Size width and height.
  3214. Size.prototype.toString = function () {
  3215. return "{W: " + this.width + ", H: " + this.height + "}";
  3216. };
  3217. /**
  3218. * Returns the string "Size"
  3219. */
  3220. Size.prototype.getClassName = function () {
  3221. return "Size";
  3222. };
  3223. /**
  3224. * Returns the Size hash code.
  3225. */
  3226. Size.prototype.getHashCode = function () {
  3227. var hash = this.width || 0;
  3228. hash = (hash * 397) ^ (this.height || 0);
  3229. return hash;
  3230. };
  3231. /**
  3232. * Updates the current size from the passed one.
  3233. * Returns the updated Size.
  3234. */
  3235. Size.prototype.copyFrom = function (src) {
  3236. this.width = src.width;
  3237. this.height = src.height;
  3238. };
  3239. /**
  3240. * Updates in place the current Size from the passed floats.
  3241. * Returns the updated Size.
  3242. */
  3243. Size.prototype.copyFromFloats = function (width, height) {
  3244. this.width = width;
  3245. this.height = height;
  3246. return this;
  3247. };
  3248. /**
  3249. * Updates in place the current Size from the passed floats.
  3250. * Returns the updated Size.
  3251. */
  3252. Size.prototype.set = function (width, height) {
  3253. return this.copyFromFloats(width, height);
  3254. };
  3255. /**
  3256. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3257. */
  3258. Size.prototype.multiplyByFloats = function (w, h) {
  3259. return new Size(this.width * w, this.height * h);
  3260. };
  3261. /**
  3262. * Returns a new Size copied from the passed one.
  3263. */
  3264. Size.prototype.clone = function () {
  3265. return new Size(this.width, this.height);
  3266. };
  3267. /**
  3268. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3269. */
  3270. Size.prototype.equals = function (other) {
  3271. if (!other) {
  3272. return false;
  3273. }
  3274. return (this.width === other.width) && (this.height === other.height);
  3275. };
  3276. Object.defineProperty(Size.prototype, "surface", {
  3277. /**
  3278. * Returns the surface of the Size : width * height (float).
  3279. */
  3280. get: function () {
  3281. return this.width * this.height;
  3282. },
  3283. enumerable: true,
  3284. configurable: true
  3285. });
  3286. /**
  3287. * Returns a new Size set to (0.0, 0.0)
  3288. */
  3289. Size.Zero = function () {
  3290. return new Size(0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Size set as the addition result of the current Size and the passed one.
  3294. */
  3295. Size.prototype.add = function (otherSize) {
  3296. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3297. return r;
  3298. };
  3299. /**
  3300. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3301. */
  3302. Size.prototype.subtract = function (otherSize) {
  3303. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3304. return r;
  3305. };
  3306. /**
  3307. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3308. */
  3309. Size.Lerp = function (start, end, amount) {
  3310. var w = start.width + ((end.width - start.width) * amount);
  3311. var h = start.height + ((end.height - start.height) * amount);
  3312. return new Size(w, h);
  3313. };
  3314. return Size;
  3315. }());
  3316. BABYLON.Size = Size;
  3317. var Quaternion = /** @class */ (function () {
  3318. /**
  3319. * Creates a new Quaternion from the passed floats.
  3320. */
  3321. function Quaternion(x, y, z, w) {
  3322. if (x === void 0) { x = 0.0; }
  3323. if (y === void 0) { y = 0.0; }
  3324. if (z === void 0) { z = 0.0; }
  3325. if (w === void 0) { w = 1.0; }
  3326. this.x = x;
  3327. this.y = y;
  3328. this.z = z;
  3329. this.w = w;
  3330. }
  3331. /**
  3332. * Returns a string with the Quaternion coordinates.
  3333. */
  3334. Quaternion.prototype.toString = function () {
  3335. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3336. };
  3337. /**
  3338. * Returns the string "Quaternion".
  3339. */
  3340. Quaternion.prototype.getClassName = function () {
  3341. return "Quaternion";
  3342. };
  3343. /**
  3344. * Returns the Quaternion hash code.
  3345. */
  3346. Quaternion.prototype.getHashCode = function () {
  3347. var hash = this.x || 0;
  3348. hash = (hash * 397) ^ (this.y || 0);
  3349. hash = (hash * 397) ^ (this.z || 0);
  3350. hash = (hash * 397) ^ (this.w || 0);
  3351. return hash;
  3352. };
  3353. /**
  3354. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3355. */
  3356. Quaternion.prototype.asArray = function () {
  3357. return [this.x, this.y, this.z, this.w];
  3358. };
  3359. /**
  3360. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3361. */
  3362. Quaternion.prototype.equals = function (otherQuaternion) {
  3363. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3364. };
  3365. /**
  3366. * Returns a new Quaternion copied from the current one.
  3367. */
  3368. Quaternion.prototype.clone = function () {
  3369. return new Quaternion(this.x, this.y, this.z, this.w);
  3370. };
  3371. /**
  3372. * Updates the current Quaternion from the passed one coordinates.
  3373. * Returns the updated Quaterion.
  3374. */
  3375. Quaternion.prototype.copyFrom = function (other) {
  3376. this.x = other.x;
  3377. this.y = other.y;
  3378. this.z = other.z;
  3379. this.w = other.w;
  3380. return this;
  3381. };
  3382. /**
  3383. * Updates the current Quaternion from the passed float coordinates.
  3384. * Returns the updated Quaterion.
  3385. */
  3386. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3387. this.x = x;
  3388. this.y = y;
  3389. this.z = z;
  3390. this.w = w;
  3391. return this;
  3392. };
  3393. /**
  3394. * Updates the current Quaternion from the passed float coordinates.
  3395. * Returns the updated Quaterion.
  3396. */
  3397. Quaternion.prototype.set = function (x, y, z, w) {
  3398. return this.copyFromFloats(x, y, z, w);
  3399. };
  3400. /**
  3401. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3402. */
  3403. Quaternion.prototype.add = function (other) {
  3404. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3405. };
  3406. /**
  3407. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3408. */
  3409. Quaternion.prototype.subtract = function (other) {
  3410. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3411. };
  3412. /**
  3413. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3414. */
  3415. Quaternion.prototype.scale = function (value) {
  3416. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3417. };
  3418. /**
  3419. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3420. */
  3421. Quaternion.prototype.multiply = function (q1) {
  3422. var result = new Quaternion(0, 0, 0, 1.0);
  3423. this.multiplyToRef(q1, result);
  3424. return result;
  3425. };
  3426. /**
  3427. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3428. * Returns the current Quaternion.
  3429. */
  3430. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3431. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3432. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3433. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3434. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3435. result.copyFromFloats(x, y, z, w);
  3436. return this;
  3437. };
  3438. /**
  3439. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3440. * Returns the updated Quaternion.
  3441. */
  3442. Quaternion.prototype.multiplyInPlace = function (q1) {
  3443. this.multiplyToRef(q1, this);
  3444. return this;
  3445. };
  3446. /**
  3447. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3448. * Returns the current Quaternion.
  3449. */
  3450. Quaternion.prototype.conjugateToRef = function (ref) {
  3451. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3452. return this;
  3453. };
  3454. /**
  3455. * Conjugates in place the current Quaternion.
  3456. * Returns the updated Quaternion.
  3457. */
  3458. Quaternion.prototype.conjugateInPlace = function () {
  3459. this.x *= -1;
  3460. this.y *= -1;
  3461. this.z *= -1;
  3462. return this;
  3463. };
  3464. /**
  3465. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3466. */
  3467. Quaternion.prototype.conjugate = function () {
  3468. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3469. return result;
  3470. };
  3471. /**
  3472. * Returns the Quaternion length (float).
  3473. */
  3474. Quaternion.prototype.length = function () {
  3475. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3476. };
  3477. /**
  3478. * Normalize in place the current Quaternion.
  3479. * Returns the updated Quaternion.
  3480. */
  3481. Quaternion.prototype.normalize = function () {
  3482. var length = 1.0 / this.length();
  3483. this.x *= length;
  3484. this.y *= length;
  3485. this.z *= length;
  3486. this.w *= length;
  3487. return this;
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3491. */
  3492. Quaternion.prototype.toEulerAngles = function (order) {
  3493. if (order === void 0) { order = "YZX"; }
  3494. var result = Vector3.Zero();
  3495. this.toEulerAnglesToRef(result, order);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3500. * Returns the current Quaternion.
  3501. */
  3502. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3503. if (order === void 0) { order = "YZX"; }
  3504. var qz = this.z;
  3505. var qx = this.x;
  3506. var qy = this.y;
  3507. var qw = this.w;
  3508. var sqw = qw * qw;
  3509. var sqz = qz * qz;
  3510. var sqx = qx * qx;
  3511. var sqy = qy * qy;
  3512. var zAxisY = qy * qz - qx * qw;
  3513. var limit = .4999999;
  3514. if (zAxisY < -limit) {
  3515. result.y = 2 * Math.atan2(qy, qw);
  3516. result.x = Math.PI / 2;
  3517. result.z = 0;
  3518. }
  3519. else if (zAxisY > limit) {
  3520. result.y = 2 * Math.atan2(qy, qw);
  3521. result.x = -Math.PI / 2;
  3522. result.z = 0;
  3523. }
  3524. else {
  3525. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3526. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3527. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3528. }
  3529. return this;
  3530. };
  3531. /**
  3532. * Updates the passed rotation matrix with the current Quaternion values.
  3533. * Returns the current Quaternion.
  3534. */
  3535. Quaternion.prototype.toRotationMatrix = function (result) {
  3536. var xx = this.x * this.x;
  3537. var yy = this.y * this.y;
  3538. var zz = this.z * this.z;
  3539. var xy = this.x * this.y;
  3540. var zw = this.z * this.w;
  3541. var zx = this.z * this.x;
  3542. var yw = this.y * this.w;
  3543. var yz = this.y * this.z;
  3544. var xw = this.x * this.w;
  3545. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3546. result.m[1] = 2.0 * (xy + zw);
  3547. result.m[2] = 2.0 * (zx - yw);
  3548. result.m[3] = 0;
  3549. result.m[4] = 2.0 * (xy - zw);
  3550. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3551. result.m[6] = 2.0 * (yz + xw);
  3552. result.m[7] = 0;
  3553. result.m[8] = 2.0 * (zx + yw);
  3554. result.m[9] = 2.0 * (yz - xw);
  3555. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3556. result.m[11] = 0;
  3557. result.m[12] = 0;
  3558. result.m[13] = 0;
  3559. result.m[14] = 0;
  3560. result.m[15] = 1.0;
  3561. result._markAsUpdated();
  3562. return this;
  3563. };
  3564. /**
  3565. * Updates the current Quaternion from the passed rotation matrix values.
  3566. * Returns the updated Quaternion.
  3567. */
  3568. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3569. Quaternion.FromRotationMatrixToRef(matrix, this);
  3570. return this;
  3571. };
  3572. // Statics
  3573. /**
  3574. * Returns a new Quaternion set from the passed rotation matrix values.
  3575. */
  3576. Quaternion.FromRotationMatrix = function (matrix) {
  3577. var result = new Quaternion();
  3578. Quaternion.FromRotationMatrixToRef(matrix, result);
  3579. return result;
  3580. };
  3581. /**
  3582. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3583. */
  3584. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3585. var data = matrix.m;
  3586. var m11 = data[0], m12 = data[4], m13 = data[8];
  3587. var m21 = data[1], m22 = data[5], m23 = data[9];
  3588. var m31 = data[2], m32 = data[6], m33 = data[10];
  3589. var trace = m11 + m22 + m33;
  3590. var s;
  3591. if (trace > 0) {
  3592. s = 0.5 / Math.sqrt(trace + 1.0);
  3593. result.w = 0.25 / s;
  3594. result.x = (m32 - m23) * s;
  3595. result.y = (m13 - m31) * s;
  3596. result.z = (m21 - m12) * s;
  3597. }
  3598. else if (m11 > m22 && m11 > m33) {
  3599. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3600. result.w = (m32 - m23) / s;
  3601. result.x = 0.25 * s;
  3602. result.y = (m12 + m21) / s;
  3603. result.z = (m13 + m31) / s;
  3604. }
  3605. else if (m22 > m33) {
  3606. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3607. result.w = (m13 - m31) / s;
  3608. result.x = (m12 + m21) / s;
  3609. result.y = 0.25 * s;
  3610. result.z = (m23 + m32) / s;
  3611. }
  3612. else {
  3613. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3614. result.w = (m21 - m12) / s;
  3615. result.x = (m13 + m31) / s;
  3616. result.y = (m23 + m32) / s;
  3617. result.z = 0.25 * s;
  3618. }
  3619. };
  3620. /**
  3621. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3622. */
  3623. Quaternion.Zero = function () {
  3624. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3625. };
  3626. /**
  3627. * Returns a new Quaternion as the inverted current Quaternion.
  3628. */
  3629. Quaternion.Inverse = function (q) {
  3630. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3631. };
  3632. /**
  3633. * Returns the identity Quaternion.
  3634. */
  3635. Quaternion.Identity = function () {
  3636. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3637. };
  3638. Quaternion.IsIdentity = function (quaternion) {
  3639. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3640. };
  3641. /**
  3642. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3643. */
  3644. Quaternion.RotationAxis = function (axis, angle) {
  3645. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3646. };
  3647. /**
  3648. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3649. */
  3650. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3651. var sin = Math.sin(angle / 2);
  3652. axis.normalize();
  3653. result.w = Math.cos(angle / 2);
  3654. result.x = axis.x * sin;
  3655. result.y = axis.y * sin;
  3656. result.z = axis.z * sin;
  3657. return result;
  3658. };
  3659. /**
  3660. * Retuns a new Quaternion set from the starting index of the passed array.
  3661. */
  3662. Quaternion.FromArray = function (array, offset) {
  3663. if (!offset) {
  3664. offset = 0;
  3665. }
  3666. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3667. };
  3668. /**
  3669. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3670. */
  3671. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3672. var q = new Quaternion();
  3673. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3674. return q;
  3675. };
  3676. /**
  3677. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3678. */
  3679. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3680. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3681. var halfRoll = roll * 0.5;
  3682. var halfPitch = pitch * 0.5;
  3683. var halfYaw = yaw * 0.5;
  3684. var sinRoll = Math.sin(halfRoll);
  3685. var cosRoll = Math.cos(halfRoll);
  3686. var sinPitch = Math.sin(halfPitch);
  3687. var cosPitch = Math.cos(halfPitch);
  3688. var sinYaw = Math.sin(halfYaw);
  3689. var cosYaw = Math.cos(halfYaw);
  3690. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3691. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3692. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3693. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3694. };
  3695. /**
  3696. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3697. */
  3698. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3699. var result = new Quaternion();
  3700. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3705. */
  3706. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3707. // Produces a quaternion from Euler angles in the z-x-z orientation
  3708. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3709. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3710. var halfBeta = beta * 0.5;
  3711. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3712. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3713. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3714. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3715. };
  3716. /**
  3717. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3718. * cf to Vector3.RotationFromAxis() documentation.
  3719. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3720. */
  3721. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3722. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3723. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3724. return quat;
  3725. };
  3726. /**
  3727. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3728. * cf to Vector3.RotationFromAxis() documentation.
  3729. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3730. */
  3731. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3732. var rotMat = MathTmp.Matrix[0];
  3733. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3734. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3735. };
  3736. Quaternion.Slerp = function (left, right, amount) {
  3737. var result = Quaternion.Identity();
  3738. Quaternion.SlerpToRef(left, right, amount, result);
  3739. return result;
  3740. };
  3741. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3742. var num2;
  3743. var num3;
  3744. var num = amount;
  3745. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3746. var flag = false;
  3747. if (num4 < 0) {
  3748. flag = true;
  3749. num4 = -num4;
  3750. }
  3751. if (num4 > 0.999999) {
  3752. num3 = 1 - num;
  3753. num2 = flag ? -num : num;
  3754. }
  3755. else {
  3756. var num5 = Math.acos(num4);
  3757. var num6 = (1.0 / Math.sin(num5));
  3758. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3759. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3760. }
  3761. result.x = (num3 * left.x) + (num2 * right.x);
  3762. result.y = (num3 * left.y) + (num2 * right.y);
  3763. result.z = (num3 * left.z) + (num2 * right.z);
  3764. result.w = (num3 * left.w) + (num2 * right.w);
  3765. };
  3766. /**
  3767. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3768. */
  3769. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3770. var squared = amount * amount;
  3771. var cubed = amount * squared;
  3772. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3773. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3774. var part3 = (cubed - (2.0 * squared)) + amount;
  3775. var part4 = cubed - squared;
  3776. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3777. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3778. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3779. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3780. return new Quaternion(x, y, z, w);
  3781. };
  3782. return Quaternion;
  3783. }());
  3784. BABYLON.Quaternion = Quaternion;
  3785. var Matrix = /** @class */ (function () {
  3786. function Matrix() {
  3787. this._isIdentity = false;
  3788. this._isIdentityDirty = true;
  3789. this.m = new Float32Array(16);
  3790. this._markAsUpdated();
  3791. }
  3792. Matrix.prototype._markAsUpdated = function () {
  3793. this.updateFlag = Matrix._updateFlagSeed++;
  3794. this._isIdentityDirty = true;
  3795. };
  3796. // Properties
  3797. /**
  3798. * Boolean : True is the matrix is the identity matrix
  3799. */
  3800. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3801. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3802. if (this._isIdentityDirty) {
  3803. this._isIdentityDirty = false;
  3804. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3805. this._isIdentity = false;
  3806. }
  3807. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3808. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3809. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3810. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3811. this._isIdentity = false;
  3812. }
  3813. else {
  3814. this._isIdentity = true;
  3815. }
  3816. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3817. this._isIdentity = false;
  3818. }
  3819. }
  3820. return this._isIdentity;
  3821. };
  3822. /**
  3823. * Returns the matrix determinant (float).
  3824. */
  3825. Matrix.prototype.determinant = function () {
  3826. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3827. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3828. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3829. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3830. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3831. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3832. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3833. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3834. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3835. };
  3836. // Methods
  3837. /**
  3838. * Returns the matrix underlying array.
  3839. */
  3840. Matrix.prototype.toArray = function () {
  3841. return this.m;
  3842. };
  3843. /**
  3844. * Returns the matrix underlying array.
  3845. */
  3846. Matrix.prototype.asArray = function () {
  3847. return this.toArray();
  3848. };
  3849. /**
  3850. * Inverts in place the Matrix.
  3851. * Returns the Matrix inverted.
  3852. */
  3853. Matrix.prototype.invert = function () {
  3854. this.invertToRef(this);
  3855. return this;
  3856. };
  3857. /**
  3858. * Sets all the matrix elements to zero.
  3859. * Returns the Matrix.
  3860. */
  3861. Matrix.prototype.reset = function () {
  3862. for (var index = 0; index < 16; index++) {
  3863. this.m[index] = 0.0;
  3864. }
  3865. this._markAsUpdated();
  3866. return this;
  3867. };
  3868. /**
  3869. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3870. */
  3871. Matrix.prototype.add = function (other) {
  3872. var result = new Matrix();
  3873. this.addToRef(other, result);
  3874. return result;
  3875. };
  3876. /**
  3877. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3878. * Returns the Matrix.
  3879. */
  3880. Matrix.prototype.addToRef = function (other, result) {
  3881. for (var index = 0; index < 16; index++) {
  3882. result.m[index] = this.m[index] + other.m[index];
  3883. }
  3884. result._markAsUpdated();
  3885. return this;
  3886. };
  3887. /**
  3888. * Adds in place the passed matrix to the current Matrix.
  3889. * Returns the updated Matrix.
  3890. */
  3891. Matrix.prototype.addToSelf = function (other) {
  3892. for (var index = 0; index < 16; index++) {
  3893. this.m[index] += other.m[index];
  3894. }
  3895. this._markAsUpdated();
  3896. return this;
  3897. };
  3898. /**
  3899. * Sets the passed matrix with the current inverted Matrix.
  3900. * Returns the unmodified current Matrix.
  3901. */
  3902. Matrix.prototype.invertToRef = function (other) {
  3903. var l1 = this.m[0];
  3904. var l2 = this.m[1];
  3905. var l3 = this.m[2];
  3906. var l4 = this.m[3];
  3907. var l5 = this.m[4];
  3908. var l6 = this.m[5];
  3909. var l7 = this.m[6];
  3910. var l8 = this.m[7];
  3911. var l9 = this.m[8];
  3912. var l10 = this.m[9];
  3913. var l11 = this.m[10];
  3914. var l12 = this.m[11];
  3915. var l13 = this.m[12];
  3916. var l14 = this.m[13];
  3917. var l15 = this.m[14];
  3918. var l16 = this.m[15];
  3919. var l17 = (l11 * l16) - (l12 * l15);
  3920. var l18 = (l10 * l16) - (l12 * l14);
  3921. var l19 = (l10 * l15) - (l11 * l14);
  3922. var l20 = (l9 * l16) - (l12 * l13);
  3923. var l21 = (l9 * l15) - (l11 * l13);
  3924. var l22 = (l9 * l14) - (l10 * l13);
  3925. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3926. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3927. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3928. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3929. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3930. var l28 = (l7 * l16) - (l8 * l15);
  3931. var l29 = (l6 * l16) - (l8 * l14);
  3932. var l30 = (l6 * l15) - (l7 * l14);
  3933. var l31 = (l5 * l16) - (l8 * l13);
  3934. var l32 = (l5 * l15) - (l7 * l13);
  3935. var l33 = (l5 * l14) - (l6 * l13);
  3936. var l34 = (l7 * l12) - (l8 * l11);
  3937. var l35 = (l6 * l12) - (l8 * l10);
  3938. var l36 = (l6 * l11) - (l7 * l10);
  3939. var l37 = (l5 * l12) - (l8 * l9);
  3940. var l38 = (l5 * l11) - (l7 * l9);
  3941. var l39 = (l5 * l10) - (l6 * l9);
  3942. other.m[0] = l23 * l27;
  3943. other.m[4] = l24 * l27;
  3944. other.m[8] = l25 * l27;
  3945. other.m[12] = l26 * l27;
  3946. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3947. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3948. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3949. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3950. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3951. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3952. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3953. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3954. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3955. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3956. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3957. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3958. other._markAsUpdated();
  3959. return this;
  3960. };
  3961. /**
  3962. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3963. * Returns the updated Matrix.
  3964. */
  3965. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3966. this.m[12] = x;
  3967. this.m[13] = y;
  3968. this.m[14] = z;
  3969. this._markAsUpdated();
  3970. return this;
  3971. };
  3972. /**
  3973. * Inserts the translation vector in the current Matrix.
  3974. * Returns the updated Matrix.
  3975. */
  3976. Matrix.prototype.setTranslation = function (vector3) {
  3977. this.m[12] = vector3.x;
  3978. this.m[13] = vector3.y;
  3979. this.m[14] = vector3.z;
  3980. this._markAsUpdated();
  3981. return this;
  3982. };
  3983. /**
  3984. * Returns a new Vector3 as the extracted translation from the Matrix.
  3985. */
  3986. Matrix.prototype.getTranslation = function () {
  3987. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3988. };
  3989. /**
  3990. * Fill a Vector3 with the extracted translation from the Matrix.
  3991. */
  3992. Matrix.prototype.getTranslationToRef = function (result) {
  3993. result.x = this.m[12];
  3994. result.y = this.m[13];
  3995. result.z = this.m[14];
  3996. return this;
  3997. };
  3998. /**
  3999. * Remove rotation and scaling part from the Matrix.
  4000. * Returns the updated Matrix.
  4001. */
  4002. Matrix.prototype.removeRotationAndScaling = function () {
  4003. this.setRowFromFloats(0, 1, 0, 0, 0);
  4004. this.setRowFromFloats(1, 0, 1, 0, 0);
  4005. this.setRowFromFloats(2, 0, 0, 1, 0);
  4006. return this;
  4007. };
  4008. /**
  4009. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4010. */
  4011. Matrix.prototype.multiply = function (other) {
  4012. var result = new Matrix();
  4013. this.multiplyToRef(other, result);
  4014. return result;
  4015. };
  4016. /**
  4017. * Updates the current Matrix from the passed one values.
  4018. * Returns the updated Matrix.
  4019. */
  4020. Matrix.prototype.copyFrom = function (other) {
  4021. for (var index = 0; index < 16; index++) {
  4022. this.m[index] = other.m[index];
  4023. }
  4024. this._markAsUpdated();
  4025. return this;
  4026. };
  4027. /**
  4028. * Populates the passed array from the starting index with the Matrix values.
  4029. * Returns the Matrix.
  4030. */
  4031. Matrix.prototype.copyToArray = function (array, offset) {
  4032. if (offset === void 0) { offset = 0; }
  4033. for (var index = 0; index < 16; index++) {
  4034. array[offset + index] = this.m[index];
  4035. }
  4036. return this;
  4037. };
  4038. /**
  4039. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4040. */
  4041. Matrix.prototype.multiplyToRef = function (other, result) {
  4042. this.multiplyToArray(other, result.m, 0);
  4043. result._markAsUpdated();
  4044. return this;
  4045. };
  4046. /**
  4047. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4048. */
  4049. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4050. var tm0 = this.m[0];
  4051. var tm1 = this.m[1];
  4052. var tm2 = this.m[2];
  4053. var tm3 = this.m[3];
  4054. var tm4 = this.m[4];
  4055. var tm5 = this.m[5];
  4056. var tm6 = this.m[6];
  4057. var tm7 = this.m[7];
  4058. var tm8 = this.m[8];
  4059. var tm9 = this.m[9];
  4060. var tm10 = this.m[10];
  4061. var tm11 = this.m[11];
  4062. var tm12 = this.m[12];
  4063. var tm13 = this.m[13];
  4064. var tm14 = this.m[14];
  4065. var tm15 = this.m[15];
  4066. var om0 = other.m[0];
  4067. var om1 = other.m[1];
  4068. var om2 = other.m[2];
  4069. var om3 = other.m[3];
  4070. var om4 = other.m[4];
  4071. var om5 = other.m[5];
  4072. var om6 = other.m[6];
  4073. var om7 = other.m[7];
  4074. var om8 = other.m[8];
  4075. var om9 = other.m[9];
  4076. var om10 = other.m[10];
  4077. var om11 = other.m[11];
  4078. var om12 = other.m[12];
  4079. var om13 = other.m[13];
  4080. var om14 = other.m[14];
  4081. var om15 = other.m[15];
  4082. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4083. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4084. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4085. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4086. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4087. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4088. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4089. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4090. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4091. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4092. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4093. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4094. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4095. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4096. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4097. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4098. return this;
  4099. };
  4100. /**
  4101. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4102. */
  4103. Matrix.prototype.equals = function (value) {
  4104. return value &&
  4105. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4106. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4107. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4108. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4109. };
  4110. /**
  4111. * Returns a new Matrix from the current Matrix.
  4112. */
  4113. Matrix.prototype.clone = function () {
  4114. 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]);
  4115. };
  4116. /**
  4117. * Returns the string "Matrix"
  4118. */
  4119. Matrix.prototype.getClassName = function () {
  4120. return "Matrix";
  4121. };
  4122. /**
  4123. * Returns the Matrix hash code.
  4124. */
  4125. Matrix.prototype.getHashCode = function () {
  4126. var hash = this.m[0] || 0;
  4127. for (var i = 1; i < 16; i++) {
  4128. hash = (hash * 397) ^ (this.m[i] || 0);
  4129. }
  4130. return hash;
  4131. };
  4132. /**
  4133. * Decomposes the current Matrix into :
  4134. * - a scale vector3 passed as a reference to update,
  4135. * - a rotation quaternion passed as a reference to update,
  4136. * - a translation vector3 passed as a reference to update.
  4137. * Returns the boolean `true`.
  4138. */
  4139. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4140. translation.x = this.m[12];
  4141. translation.y = this.m[13];
  4142. translation.z = this.m[14];
  4143. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4144. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4145. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4146. if (this.determinant() <= 0) {
  4147. scale.y *= -1;
  4148. }
  4149. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4150. rotation.x = 0;
  4151. rotation.y = 0;
  4152. rotation.z = 0;
  4153. rotation.w = 1;
  4154. return false;
  4155. }
  4156. 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]);
  4157. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4158. return true;
  4159. };
  4160. /**
  4161. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4162. */
  4163. Matrix.prototype.getRotationMatrix = function () {
  4164. var result = Matrix.Identity();
  4165. this.getRotationMatrixToRef(result);
  4166. return result;
  4167. };
  4168. /**
  4169. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4170. * Returns the current Matrix.
  4171. */
  4172. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4173. var m = this.m;
  4174. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4175. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4176. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4177. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4178. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4179. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4180. 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);
  4181. return this;
  4182. };
  4183. // Statics
  4184. /**
  4185. * Returns a new Matrix set from the starting index of the passed array.
  4186. */
  4187. Matrix.FromArray = function (array, offset) {
  4188. var result = new Matrix();
  4189. if (!offset) {
  4190. offset = 0;
  4191. }
  4192. Matrix.FromArrayToRef(array, offset, result);
  4193. return result;
  4194. };
  4195. /**
  4196. * Sets the passed "result" matrix from the starting index of the passed array.
  4197. */
  4198. Matrix.FromArrayToRef = function (array, offset, result) {
  4199. for (var index = 0; index < 16; index++) {
  4200. result.m[index] = array[index + offset];
  4201. }
  4202. result._markAsUpdated();
  4203. };
  4204. /**
  4205. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4206. */
  4207. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4208. for (var index = 0; index < 16; index++) {
  4209. result.m[index] = array[index + offset] * scale;
  4210. }
  4211. result._markAsUpdated();
  4212. };
  4213. /**
  4214. * Sets the passed matrix "result" with the 16 passed floats.
  4215. */
  4216. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4217. result.m[0] = initialM11;
  4218. result.m[1] = initialM12;
  4219. result.m[2] = initialM13;
  4220. result.m[3] = initialM14;
  4221. result.m[4] = initialM21;
  4222. result.m[5] = initialM22;
  4223. result.m[6] = initialM23;
  4224. result.m[7] = initialM24;
  4225. result.m[8] = initialM31;
  4226. result.m[9] = initialM32;
  4227. result.m[10] = initialM33;
  4228. result.m[11] = initialM34;
  4229. result.m[12] = initialM41;
  4230. result.m[13] = initialM42;
  4231. result.m[14] = initialM43;
  4232. result.m[15] = initialM44;
  4233. result._markAsUpdated();
  4234. };
  4235. /**
  4236. * Returns the index-th row of the current matrix as a new Vector4.
  4237. */
  4238. Matrix.prototype.getRow = function (index) {
  4239. if (index < 0 || index > 3) {
  4240. return null;
  4241. }
  4242. var i = index * 4;
  4243. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4244. };
  4245. /**
  4246. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4247. * Returns the updated Matrix.
  4248. */
  4249. Matrix.prototype.setRow = function (index, row) {
  4250. if (index < 0 || index > 3) {
  4251. return this;
  4252. }
  4253. var i = index * 4;
  4254. this.m[i + 0] = row.x;
  4255. this.m[i + 1] = row.y;
  4256. this.m[i + 2] = row.z;
  4257. this.m[i + 3] = row.w;
  4258. this._markAsUpdated();
  4259. return this;
  4260. };
  4261. /**
  4262. * Compute the transpose of the matrix.
  4263. * Returns a new Matrix.
  4264. */
  4265. Matrix.prototype.transpose = function () {
  4266. return Matrix.Transpose(this);
  4267. };
  4268. /**
  4269. * Compute the transpose of the matrix.
  4270. * Returns the current matrix.
  4271. */
  4272. Matrix.prototype.transposeToRef = function (result) {
  4273. Matrix.TransposeToRef(this, result);
  4274. return this;
  4275. };
  4276. /**
  4277. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4278. * Returns the updated Matrix.
  4279. */
  4280. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4281. if (index < 0 || index > 3) {
  4282. return this;
  4283. }
  4284. var i = index * 4;
  4285. this.m[i + 0] = x;
  4286. this.m[i + 1] = y;
  4287. this.m[i + 2] = z;
  4288. this.m[i + 3] = w;
  4289. this._markAsUpdated();
  4290. return this;
  4291. };
  4292. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4293. /**
  4294. * Static identity matrix to be used as readonly matrix
  4295. * Must not be updated.
  4296. */
  4297. get: function () {
  4298. return Matrix._identityReadOnly;
  4299. },
  4300. enumerable: true,
  4301. configurable: true
  4302. });
  4303. /**
  4304. * Returns a new Matrix set from the 16 passed floats.
  4305. */
  4306. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4307. var result = new Matrix();
  4308. result.m[0] = initialM11;
  4309. result.m[1] = initialM12;
  4310. result.m[2] = initialM13;
  4311. result.m[3] = initialM14;
  4312. result.m[4] = initialM21;
  4313. result.m[5] = initialM22;
  4314. result.m[6] = initialM23;
  4315. result.m[7] = initialM24;
  4316. result.m[8] = initialM31;
  4317. result.m[9] = initialM32;
  4318. result.m[10] = initialM33;
  4319. result.m[11] = initialM34;
  4320. result.m[12] = initialM41;
  4321. result.m[13] = initialM42;
  4322. result.m[14] = initialM43;
  4323. result.m[15] = initialM44;
  4324. return result;
  4325. };
  4326. /**
  4327. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4328. */
  4329. Matrix.Compose = function (scale, rotation, translation) {
  4330. var result = Matrix.Identity();
  4331. Matrix.ComposeToRef(scale, rotation, translation, result);
  4332. return result;
  4333. };
  4334. /**
  4335. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4336. */
  4337. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4338. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4339. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4340. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4341. result.setTranslation(translation);
  4342. };
  4343. /**
  4344. * Returns a new indentity Matrix.
  4345. */
  4346. Matrix.Identity = function () {
  4347. 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);
  4348. };
  4349. /**
  4350. * Sets the passed "result" as an identity matrix.
  4351. */
  4352. Matrix.IdentityToRef = function (result) {
  4353. 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);
  4354. };
  4355. /**
  4356. * Returns a new zero Matrix.
  4357. */
  4358. Matrix.Zero = function () {
  4359. 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);
  4360. };
  4361. /**
  4362. * Returns a new rotation matrix for "angle" radians around the X axis.
  4363. */
  4364. Matrix.RotationX = function (angle) {
  4365. var result = new Matrix();
  4366. Matrix.RotationXToRef(angle, result);
  4367. return result;
  4368. };
  4369. /**
  4370. * Returns a new Matrix as the passed inverted one.
  4371. */
  4372. Matrix.Invert = function (source) {
  4373. var result = new Matrix();
  4374. source.invertToRef(result);
  4375. return result;
  4376. };
  4377. /**
  4378. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4379. */
  4380. Matrix.RotationXToRef = function (angle, result) {
  4381. var s = Math.sin(angle);
  4382. var c = Math.cos(angle);
  4383. result.m[0] = 1.0;
  4384. result.m[15] = 1.0;
  4385. result.m[5] = c;
  4386. result.m[10] = c;
  4387. result.m[9] = -s;
  4388. result.m[6] = s;
  4389. result.m[1] = 0.0;
  4390. result.m[2] = 0.0;
  4391. result.m[3] = 0.0;
  4392. result.m[4] = 0.0;
  4393. result.m[7] = 0.0;
  4394. result.m[8] = 0.0;
  4395. result.m[11] = 0.0;
  4396. result.m[12] = 0.0;
  4397. result.m[13] = 0.0;
  4398. result.m[14] = 0.0;
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4403. */
  4404. Matrix.RotationY = function (angle) {
  4405. var result = new Matrix();
  4406. Matrix.RotationYToRef(angle, result);
  4407. return result;
  4408. };
  4409. /**
  4410. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4411. */
  4412. Matrix.RotationYToRef = function (angle, result) {
  4413. var s = Math.sin(angle);
  4414. var c = Math.cos(angle);
  4415. result.m[5] = 1.0;
  4416. result.m[15] = 1.0;
  4417. result.m[0] = c;
  4418. result.m[2] = -s;
  4419. result.m[8] = s;
  4420. result.m[10] = c;
  4421. result.m[1] = 0.0;
  4422. result.m[3] = 0.0;
  4423. result.m[4] = 0.0;
  4424. result.m[6] = 0.0;
  4425. result.m[7] = 0.0;
  4426. result.m[9] = 0.0;
  4427. result.m[11] = 0.0;
  4428. result.m[12] = 0.0;
  4429. result.m[13] = 0.0;
  4430. result.m[14] = 0.0;
  4431. result._markAsUpdated();
  4432. };
  4433. /**
  4434. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4435. */
  4436. Matrix.RotationZ = function (angle) {
  4437. var result = new Matrix();
  4438. Matrix.RotationZToRef(angle, result);
  4439. return result;
  4440. };
  4441. /**
  4442. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4443. */
  4444. Matrix.RotationZToRef = function (angle, result) {
  4445. var s = Math.sin(angle);
  4446. var c = Math.cos(angle);
  4447. result.m[10] = 1.0;
  4448. result.m[15] = 1.0;
  4449. result.m[0] = c;
  4450. result.m[1] = s;
  4451. result.m[4] = -s;
  4452. result.m[5] = c;
  4453. result.m[2] = 0.0;
  4454. result.m[3] = 0.0;
  4455. result.m[6] = 0.0;
  4456. result.m[7] = 0.0;
  4457. result.m[8] = 0.0;
  4458. result.m[9] = 0.0;
  4459. result.m[11] = 0.0;
  4460. result.m[12] = 0.0;
  4461. result.m[13] = 0.0;
  4462. result.m[14] = 0.0;
  4463. result._markAsUpdated();
  4464. };
  4465. /**
  4466. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4467. */
  4468. Matrix.RotationAxis = function (axis, angle) {
  4469. var result = Matrix.Zero();
  4470. Matrix.RotationAxisToRef(axis, angle, result);
  4471. return result;
  4472. };
  4473. /**
  4474. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4475. */
  4476. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4477. var s = Math.sin(-angle);
  4478. var c = Math.cos(-angle);
  4479. var c1 = 1 - c;
  4480. axis.normalize();
  4481. result.m[0] = (axis.x * axis.x) * c1 + c;
  4482. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4483. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4484. result.m[3] = 0.0;
  4485. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4486. result.m[5] = (axis.y * axis.y) * c1 + c;
  4487. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4488. result.m[7] = 0.0;
  4489. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4490. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4491. result.m[10] = (axis.z * axis.z) * c1 + c;
  4492. result.m[11] = 0.0;
  4493. result.m[15] = 1.0;
  4494. result._markAsUpdated();
  4495. };
  4496. /**
  4497. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4498. */
  4499. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4500. var result = new Matrix();
  4501. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4502. return result;
  4503. };
  4504. /**
  4505. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4506. */
  4507. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4508. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4509. this._tempQuaternion.toRotationMatrix(result);
  4510. };
  4511. /**
  4512. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4513. */
  4514. Matrix.Scaling = function (x, y, z) {
  4515. var result = Matrix.Zero();
  4516. Matrix.ScalingToRef(x, y, z, result);
  4517. return result;
  4518. };
  4519. /**
  4520. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4521. */
  4522. Matrix.ScalingToRef = function (x, y, z, result) {
  4523. result.m[0] = x;
  4524. result.m[1] = 0.0;
  4525. result.m[2] = 0.0;
  4526. result.m[3] = 0.0;
  4527. result.m[4] = 0.0;
  4528. result.m[5] = y;
  4529. result.m[6] = 0.0;
  4530. result.m[7] = 0.0;
  4531. result.m[8] = 0.0;
  4532. result.m[9] = 0.0;
  4533. result.m[10] = z;
  4534. result.m[11] = 0.0;
  4535. result.m[12] = 0.0;
  4536. result.m[13] = 0.0;
  4537. result.m[14] = 0.0;
  4538. result.m[15] = 1.0;
  4539. result._markAsUpdated();
  4540. };
  4541. /**
  4542. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4543. */
  4544. Matrix.Translation = function (x, y, z) {
  4545. var result = Matrix.Identity();
  4546. Matrix.TranslationToRef(x, y, z, result);
  4547. return result;
  4548. };
  4549. /**
  4550. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4551. */
  4552. Matrix.TranslationToRef = function (x, y, z, result) {
  4553. 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);
  4554. };
  4555. /**
  4556. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4557. */
  4558. Matrix.Lerp = function (startValue, endValue, gradient) {
  4559. var result = Matrix.Zero();
  4560. for (var index = 0; index < 16; index++) {
  4561. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4562. }
  4563. result._markAsUpdated();
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix whose values are computed by :
  4568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4571. */
  4572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4573. var startScale = new Vector3(0, 0, 0);
  4574. var startRotation = new Quaternion();
  4575. var startTranslation = new Vector3(0, 0, 0);
  4576. startValue.decompose(startScale, startRotation, startTranslation);
  4577. var endScale = new Vector3(0, 0, 0);
  4578. var endRotation = new Quaternion();
  4579. var endTranslation = new Vector3(0, 0, 0);
  4580. endValue.decompose(endScale, endRotation, endTranslation);
  4581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4585. };
  4586. /**
  4587. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4588. * This methods works for a Left-Handed system.
  4589. */
  4590. Matrix.LookAtLH = function (eye, target, up) {
  4591. var result = Matrix.Zero();
  4592. Matrix.LookAtLHToRef(eye, target, up, result);
  4593. return result;
  4594. };
  4595. /**
  4596. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4597. * This methods works for a Left-Handed system.
  4598. */
  4599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4600. // Z axis
  4601. target.subtractToRef(eye, this._zAxis);
  4602. this._zAxis.normalize();
  4603. // X axis
  4604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4605. if (this._xAxis.lengthSquared() === 0) {
  4606. this._xAxis.x = 1.0;
  4607. }
  4608. else {
  4609. this._xAxis.normalize();
  4610. }
  4611. // Y axis
  4612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4613. this._yAxis.normalize();
  4614. // Eye angles
  4615. var ex = -Vector3.Dot(this._xAxis, eye);
  4616. var ey = -Vector3.Dot(this._yAxis, eye);
  4617. var ez = -Vector3.Dot(this._zAxis, eye);
  4618. 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);
  4619. };
  4620. /**
  4621. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4622. * This methods works for a Right-Handed system.
  4623. */
  4624. Matrix.LookAtRH = function (eye, target, up) {
  4625. var result = Matrix.Zero();
  4626. Matrix.LookAtRHToRef(eye, target, up, result);
  4627. return result;
  4628. };
  4629. /**
  4630. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4631. * This methods works for a Left-Handed system.
  4632. */
  4633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4634. // Z axis
  4635. eye.subtractToRef(target, this._zAxis);
  4636. this._zAxis.normalize();
  4637. // X axis
  4638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4639. if (this._xAxis.lengthSquared() === 0) {
  4640. this._xAxis.x = 1.0;
  4641. }
  4642. else {
  4643. this._xAxis.normalize();
  4644. }
  4645. // Y axis
  4646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4647. this._yAxis.normalize();
  4648. // Eye angles
  4649. var ex = -Vector3.Dot(this._xAxis, eye);
  4650. var ey = -Vector3.Dot(this._yAxis, eye);
  4651. var ez = -Vector3.Dot(this._zAxis, eye);
  4652. 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);
  4653. };
  4654. /**
  4655. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4656. */
  4657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4658. var matrix = Matrix.Zero();
  4659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4660. return matrix;
  4661. };
  4662. /**
  4663. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4664. */
  4665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4666. var n = znear;
  4667. var f = zfar;
  4668. var a = 2.0 / width;
  4669. var b = 2.0 / height;
  4670. var c = 2.0 / (f - n);
  4671. var d = -(f + n) / (f - n);
  4672. 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);
  4673. };
  4674. /**
  4675. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4676. */
  4677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4678. var matrix = Matrix.Zero();
  4679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4680. return matrix;
  4681. };
  4682. /**
  4683. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4684. */
  4685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4686. var n = znear;
  4687. var f = zfar;
  4688. var a = 2.0 / (right - left);
  4689. var b = 2.0 / (top - bottom);
  4690. var c = 2.0 / (f - n);
  4691. var d = -(f + n) / (f - n);
  4692. var i0 = (left + right) / (left - right);
  4693. var i1 = (top + bottom) / (bottom - top);
  4694. 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);
  4695. };
  4696. /**
  4697. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4698. */
  4699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4700. var matrix = Matrix.Zero();
  4701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4702. return matrix;
  4703. };
  4704. /**
  4705. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4706. */
  4707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4709. result.m[10] *= -1.0;
  4710. };
  4711. /**
  4712. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4713. */
  4714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4715. var matrix = Matrix.Zero();
  4716. var n = znear;
  4717. var f = zfar;
  4718. var a = 2.0 * n / width;
  4719. var b = 2.0 * n / height;
  4720. var c = (f + n) / (f - n);
  4721. var d = -2.0 * f * n / (f - n);
  4722. 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);
  4723. return matrix;
  4724. };
  4725. /**
  4726. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4727. */
  4728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4729. var matrix = Matrix.Zero();
  4730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4731. return matrix;
  4732. };
  4733. /**
  4734. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4735. */
  4736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4738. var n = znear;
  4739. var f = zfar;
  4740. var t = 1.0 / (Math.tan(fov * 0.5));
  4741. var a = isVerticalFovFixed ? (t / aspect) : t;
  4742. var b = isVerticalFovFixed ? t : (t * aspect);
  4743. var c = (f + n) / (f - n);
  4744. var d = -2.0 * f * n / (f - n);
  4745. 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);
  4746. };
  4747. /**
  4748. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4749. */
  4750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4751. var matrix = Matrix.Zero();
  4752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4753. return matrix;
  4754. };
  4755. /**
  4756. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4757. */
  4758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4759. //alternatively this could be expressed as:
  4760. // m = PerspectiveFovLHToRef
  4761. // m[10] *= -1.0;
  4762. // m[11] *= -1.0;
  4763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4764. var n = znear;
  4765. var f = zfar;
  4766. var t = 1.0 / (Math.tan(fov * 0.5));
  4767. var a = isVerticalFovFixed ? (t / aspect) : t;
  4768. var b = isVerticalFovFixed ? t : (t * aspect);
  4769. var c = -(f + n) / (f - n);
  4770. var d = -2 * f * n / (f - n);
  4771. 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);
  4772. };
  4773. /**
  4774. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4775. */
  4776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4777. if (rightHanded === void 0) { rightHanded = false; }
  4778. var rightHandedFactor = rightHanded ? -1 : 1;
  4779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4783. var xScale = 2.0 / (leftTan + rightTan);
  4784. var yScale = 2.0 / (upTan + downTan);
  4785. result.m[0] = xScale;
  4786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4787. result.m[5] = yScale;
  4788. result.m[6] = result.m[7] = 0.0;
  4789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4792. result.m[10] = -zfar / (znear - zfar);
  4793. result.m[11] = 1.0 * rightHandedFactor;
  4794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4796. // result.m[14] = (znear * zfar) / (znear - zfar);
  4797. result._markAsUpdated();
  4798. };
  4799. /**
  4800. * Returns the final transformation matrix : world * view * projection * viewport
  4801. */
  4802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4803. var cw = viewport.width;
  4804. var ch = viewport.height;
  4805. var cx = viewport.x;
  4806. var cy = viewport.y;
  4807. 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);
  4808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4809. };
  4810. /**
  4811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4812. */
  4813. Matrix.GetAsMatrix2x2 = function (matrix) {
  4814. return new Float32Array([
  4815. matrix.m[0], matrix.m[1],
  4816. matrix.m[4], matrix.m[5]
  4817. ]);
  4818. };
  4819. /**
  4820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4821. */
  4822. Matrix.GetAsMatrix3x3 = function (matrix) {
  4823. return new Float32Array([
  4824. matrix.m[0], matrix.m[1], matrix.m[2],
  4825. matrix.m[4], matrix.m[5], matrix.m[6],
  4826. matrix.m[8], matrix.m[9], matrix.m[10]
  4827. ]);
  4828. };
  4829. /**
  4830. * Compute the transpose of the passed Matrix.
  4831. * Returns a new Matrix.
  4832. */
  4833. Matrix.Transpose = function (matrix) {
  4834. var result = new Matrix();
  4835. Matrix.TransposeToRef(matrix, result);
  4836. return result;
  4837. };
  4838. /**
  4839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4840. */
  4841. Matrix.TransposeToRef = function (matrix, result) {
  4842. result.m[0] = matrix.m[0];
  4843. result.m[1] = matrix.m[4];
  4844. result.m[2] = matrix.m[8];
  4845. result.m[3] = matrix.m[12];
  4846. result.m[4] = matrix.m[1];
  4847. result.m[5] = matrix.m[5];
  4848. result.m[6] = matrix.m[9];
  4849. result.m[7] = matrix.m[13];
  4850. result.m[8] = matrix.m[2];
  4851. result.m[9] = matrix.m[6];
  4852. result.m[10] = matrix.m[10];
  4853. result.m[11] = matrix.m[14];
  4854. result.m[12] = matrix.m[3];
  4855. result.m[13] = matrix.m[7];
  4856. result.m[14] = matrix.m[11];
  4857. result.m[15] = matrix.m[15];
  4858. };
  4859. /**
  4860. * Returns a new Matrix as the reflection matrix across the passed plane.
  4861. */
  4862. Matrix.Reflection = function (plane) {
  4863. var matrix = new Matrix();
  4864. Matrix.ReflectionToRef(plane, matrix);
  4865. return matrix;
  4866. };
  4867. /**
  4868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4869. */
  4870. Matrix.ReflectionToRef = function (plane, result) {
  4871. plane.normalize();
  4872. var x = plane.normal.x;
  4873. var y = plane.normal.y;
  4874. var z = plane.normal.z;
  4875. var temp = -2 * x;
  4876. var temp2 = -2 * y;
  4877. var temp3 = -2 * z;
  4878. result.m[0] = (temp * x) + 1;
  4879. result.m[1] = temp2 * x;
  4880. result.m[2] = temp3 * x;
  4881. result.m[3] = 0.0;
  4882. result.m[4] = temp * y;
  4883. result.m[5] = (temp2 * y) + 1;
  4884. result.m[6] = temp3 * y;
  4885. result.m[7] = 0.0;
  4886. result.m[8] = temp * z;
  4887. result.m[9] = temp2 * z;
  4888. result.m[10] = (temp3 * z) + 1;
  4889. result.m[11] = 0.0;
  4890. result.m[12] = temp * plane.d;
  4891. result.m[13] = temp2 * plane.d;
  4892. result.m[14] = temp3 * plane.d;
  4893. result.m[15] = 1.0;
  4894. result._markAsUpdated();
  4895. };
  4896. /**
  4897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4898. */
  4899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4900. result.m[0] = xaxis.x;
  4901. result.m[1] = xaxis.y;
  4902. result.m[2] = xaxis.z;
  4903. result.m[3] = 0.0;
  4904. result.m[4] = yaxis.x;
  4905. result.m[5] = yaxis.y;
  4906. result.m[6] = yaxis.z;
  4907. result.m[7] = 0.0;
  4908. result.m[8] = zaxis.x;
  4909. result.m[9] = zaxis.y;
  4910. result.m[10] = zaxis.z;
  4911. result.m[11] = 0.0;
  4912. result.m[12] = 0.0;
  4913. result.m[13] = 0.0;
  4914. result.m[14] = 0.0;
  4915. result.m[15] = 1.0;
  4916. result._markAsUpdated();
  4917. };
  4918. /**
  4919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4920. */
  4921. Matrix.FromQuaternionToRef = function (quat, result) {
  4922. var xx = quat.x * quat.x;
  4923. var yy = quat.y * quat.y;
  4924. var zz = quat.z * quat.z;
  4925. var xy = quat.x * quat.y;
  4926. var zw = quat.z * quat.w;
  4927. var zx = quat.z * quat.x;
  4928. var yw = quat.y * quat.w;
  4929. var yz = quat.y * quat.z;
  4930. var xw = quat.x * quat.w;
  4931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4932. result.m[1] = 2.0 * (xy + zw);
  4933. result.m[2] = 2.0 * (zx - yw);
  4934. result.m[3] = 0.0;
  4935. result.m[4] = 2.0 * (xy - zw);
  4936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4937. result.m[6] = 2.0 * (yz + xw);
  4938. result.m[7] = 0.0;
  4939. result.m[8] = 2.0 * (zx + yw);
  4940. result.m[9] = 2.0 * (yz - xw);
  4941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4942. result.m[11] = 0.0;
  4943. result.m[12] = 0.0;
  4944. result.m[13] = 0.0;
  4945. result.m[14] = 0.0;
  4946. result.m[15] = 1.0;
  4947. result._markAsUpdated();
  4948. };
  4949. Matrix._tempQuaternion = new Quaternion();
  4950. Matrix._xAxis = Vector3.Zero();
  4951. Matrix._yAxis = Vector3.Zero();
  4952. Matrix._zAxis = Vector3.Zero();
  4953. Matrix._updateFlagSeed = 0;
  4954. Matrix._identityReadOnly = Matrix.Identity();
  4955. return Matrix;
  4956. }());
  4957. BABYLON.Matrix = Matrix;
  4958. var Plane = /** @class */ (function () {
  4959. /**
  4960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4961. */
  4962. function Plane(a, b, c, d) {
  4963. this.normal = new Vector3(a, b, c);
  4964. this.d = d;
  4965. }
  4966. /**
  4967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4968. */
  4969. Plane.prototype.asArray = function () {
  4970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4971. };
  4972. // Methods
  4973. /**
  4974. * Returns a new plane copied from the current Plane.
  4975. */
  4976. Plane.prototype.clone = function () {
  4977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4978. };
  4979. /**
  4980. * Returns the string "Plane".
  4981. */
  4982. Plane.prototype.getClassName = function () {
  4983. return "Plane";
  4984. };
  4985. /**
  4986. * Returns the Plane hash code.
  4987. */
  4988. Plane.prototype.getHashCode = function () {
  4989. var hash = this.normal.getHashCode();
  4990. hash = (hash * 397) ^ (this.d || 0);
  4991. return hash;
  4992. };
  4993. /**
  4994. * Normalize the current Plane in place.
  4995. * Returns the updated Plane.
  4996. */
  4997. Plane.prototype.normalize = function () {
  4998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4999. var magnitude = 0.0;
  5000. if (norm !== 0) {
  5001. magnitude = 1.0 / norm;
  5002. }
  5003. this.normal.x *= magnitude;
  5004. this.normal.y *= magnitude;
  5005. this.normal.z *= magnitude;
  5006. this.d *= magnitude;
  5007. return this;
  5008. };
  5009. /**
  5010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5011. */
  5012. Plane.prototype.transform = function (transformation) {
  5013. var transposedMatrix = Matrix.Transpose(transformation);
  5014. var x = this.normal.x;
  5015. var y = this.normal.y;
  5016. var z = this.normal.z;
  5017. var d = this.d;
  5018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5022. return new Plane(normalX, normalY, normalZ, finalD);
  5023. };
  5024. /**
  5025. * Returns the dot product (float) of the point coordinates and the plane normal.
  5026. */
  5027. Plane.prototype.dotCoordinate = function (point) {
  5028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5029. };
  5030. /**
  5031. * Updates the current Plane from the plane defined by the three passed points.
  5032. * Returns the updated Plane.
  5033. */
  5034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5035. var x1 = point2.x - point1.x;
  5036. var y1 = point2.y - point1.y;
  5037. var z1 = point2.z - point1.z;
  5038. var x2 = point3.x - point1.x;
  5039. var y2 = point3.y - point1.y;
  5040. var z2 = point3.z - point1.z;
  5041. var yz = (y1 * z2) - (z1 * y2);
  5042. var xz = (z1 * x2) - (x1 * z2);
  5043. var xy = (x1 * y2) - (y1 * x2);
  5044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5045. var invPyth;
  5046. if (pyth !== 0) {
  5047. invPyth = 1.0 / pyth;
  5048. }
  5049. else {
  5050. invPyth = 0.0;
  5051. }
  5052. this.normal.x = yz * invPyth;
  5053. this.normal.y = xz * invPyth;
  5054. this.normal.z = xy * invPyth;
  5055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5056. return this;
  5057. };
  5058. /**
  5059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5060. */
  5061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5062. var dot = Vector3.Dot(this.normal, direction);
  5063. return (dot <= epsilon);
  5064. };
  5065. /**
  5066. * Returns the signed distance (float) from the passed point to the Plane.
  5067. */
  5068. Plane.prototype.signedDistanceTo = function (point) {
  5069. return Vector3.Dot(point, this.normal) + this.d;
  5070. };
  5071. // Statics
  5072. /**
  5073. * Returns a new Plane from the passed array.
  5074. */
  5075. Plane.FromArray = function (array) {
  5076. return new Plane(array[0], array[1], array[2], array[3]);
  5077. };
  5078. /**
  5079. * Returns a new Plane defined by the three passed points.
  5080. */
  5081. Plane.FromPoints = function (point1, point2, point3) {
  5082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5083. result.copyFromPoints(point1, point2, point3);
  5084. return result;
  5085. };
  5086. /**
  5087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5088. * Note : the vector "normal" is updated because normalized.
  5089. */
  5090. Plane.FromPositionAndNormal = function (origin, normal) {
  5091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5092. normal.normalize();
  5093. result.normal = normal;
  5094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5095. return result;
  5096. };
  5097. /**
  5098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5099. */
  5100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5102. return Vector3.Dot(point, normal) + d;
  5103. };
  5104. return Plane;
  5105. }());
  5106. BABYLON.Plane = Plane;
  5107. var Viewport = /** @class */ (function () {
  5108. /**
  5109. * Creates a Viewport object located at (x, y) and sized (width, height).
  5110. */
  5111. function Viewport(x, y, width, height) {
  5112. this.x = x;
  5113. this.y = y;
  5114. this.width = width;
  5115. this.height = height;
  5116. }
  5117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5118. if (renderWidthOrEngine.getRenderWidth) {
  5119. var engine = renderWidthOrEngine;
  5120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5121. }
  5122. var renderWidth = renderWidthOrEngine;
  5123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5124. };
  5125. /**
  5126. * Returns a new Viewport copied from the current one.
  5127. */
  5128. Viewport.prototype.clone = function () {
  5129. return new Viewport(this.x, this.y, this.width, this.height);
  5130. };
  5131. return Viewport;
  5132. }());
  5133. BABYLON.Viewport = Viewport;
  5134. var Frustum = /** @class */ (function () {
  5135. function Frustum() {
  5136. }
  5137. /**
  5138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5139. */
  5140. Frustum.GetPlanes = function (transform) {
  5141. var frustumPlanes = [];
  5142. for (var index = 0; index < 6; index++) {
  5143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5144. }
  5145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5146. return frustumPlanes;
  5147. };
  5148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5152. frustumPlane.d = transform.m[15] + transform.m[14];
  5153. frustumPlane.normalize();
  5154. };
  5155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5159. frustumPlane.d = transform.m[15] - transform.m[14];
  5160. frustumPlane.normalize();
  5161. };
  5162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5166. frustumPlane.d = transform.m[15] + transform.m[12];
  5167. frustumPlane.normalize();
  5168. };
  5169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5173. frustumPlane.d = transform.m[15] - transform.m[12];
  5174. frustumPlane.normalize();
  5175. };
  5176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5180. frustumPlane.d = transform.m[15] - transform.m[13];
  5181. frustumPlane.normalize();
  5182. };
  5183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5187. frustumPlane.d = transform.m[15] + transform.m[13];
  5188. frustumPlane.normalize();
  5189. };
  5190. /**
  5191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5192. */
  5193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5194. // Near
  5195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5196. // Far
  5197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5198. // Left
  5199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5200. // Right
  5201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5202. // Top
  5203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5204. // Bottom
  5205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5206. };
  5207. return Frustum;
  5208. }());
  5209. BABYLON.Frustum = Frustum;
  5210. var Space;
  5211. (function (Space) {
  5212. Space[Space["LOCAL"] = 0] = "LOCAL";
  5213. Space[Space["WORLD"] = 1] = "WORLD";
  5214. Space[Space["BONE"] = 2] = "BONE";
  5215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5216. var Axis = /** @class */ (function () {
  5217. function Axis() {
  5218. }
  5219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5222. return Axis;
  5223. }());
  5224. BABYLON.Axis = Axis;
  5225. ;
  5226. var BezierCurve = /** @class */ (function () {
  5227. function BezierCurve() {
  5228. }
  5229. /**
  5230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5231. */
  5232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5233. // Extract X (which is equal to time here)
  5234. var f0 = 1 - 3 * x2 + 3 * x1;
  5235. var f1 = 3 * x2 - 6 * x1;
  5236. var f2 = 3 * x1;
  5237. var refinedT = t;
  5238. for (var i = 0; i < 5; i++) {
  5239. var refinedT2 = refinedT * refinedT;
  5240. var refinedT3 = refinedT2 * refinedT;
  5241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5243. refinedT -= (x - t) * slope;
  5244. refinedT = Math.min(1, Math.max(0, refinedT));
  5245. }
  5246. // Resolve cubic bezier for the given x
  5247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5249. Math.pow(refinedT, 3);
  5250. };
  5251. return BezierCurve;
  5252. }());
  5253. BABYLON.BezierCurve = BezierCurve;
  5254. var Orientation;
  5255. (function (Orientation) {
  5256. Orientation[Orientation["CW"] = 0] = "CW";
  5257. Orientation[Orientation["CCW"] = 1] = "CCW";
  5258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5259. var Angle = /** @class */ (function () {
  5260. /**
  5261. * Creates an Angle object of "radians" radians (float).
  5262. */
  5263. function Angle(radians) {
  5264. var _this = this;
  5265. /**
  5266. * Returns the Angle value in degrees (float).
  5267. */
  5268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5269. /**
  5270. * Returns the Angle value in radians (float).
  5271. */
  5272. this.radians = function () { return _this._radians; };
  5273. this._radians = radians;
  5274. if (this._radians < 0.0)
  5275. this._radians += (2.0 * Math.PI);
  5276. }
  5277. /**
  5278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5279. */
  5280. Angle.BetweenTwoPoints = function (a, b) {
  5281. var delta = b.subtract(a);
  5282. var theta = Math.atan2(delta.y, delta.x);
  5283. return new Angle(theta);
  5284. };
  5285. /**
  5286. * Returns a new Angle object from the passed float in radians.
  5287. */
  5288. Angle.FromRadians = function (radians) {
  5289. return new Angle(radians);
  5290. };
  5291. /**
  5292. * Returns a new Angle object from the passed float in degrees.
  5293. */
  5294. Angle.FromDegrees = function (degrees) {
  5295. return new Angle(degrees * Math.PI / 180.0);
  5296. };
  5297. return Angle;
  5298. }());
  5299. BABYLON.Angle = Angle;
  5300. var Arc2 = /** @class */ (function () {
  5301. /**
  5302. * Creates an Arc object from the three passed points : start, middle and end.
  5303. */
  5304. function Arc2(startPoint, midPoint, endPoint) {
  5305. this.startPoint = startPoint;
  5306. this.midPoint = midPoint;
  5307. this.endPoint = endPoint;
  5308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5312. 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);
  5313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5315. var a1 = this.startAngle.degrees();
  5316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5318. // angles correction
  5319. if (a2 - a1 > +180.0)
  5320. a2 -= 360.0;
  5321. if (a2 - a1 < -180.0)
  5322. a2 += 360.0;
  5323. if (a3 - a2 > +180.0)
  5324. a3 -= 360.0;
  5325. if (a3 - a2 < -180.0)
  5326. a3 += 360.0;
  5327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5329. }
  5330. return Arc2;
  5331. }());
  5332. BABYLON.Arc2 = Arc2;
  5333. var Path2 = /** @class */ (function () {
  5334. /**
  5335. * Creates a Path2 object from the starting 2D coordinates x and y.
  5336. */
  5337. function Path2(x, y) {
  5338. this._points = new Array();
  5339. this._length = 0.0;
  5340. this.closed = false;
  5341. this._points.push(new Vector2(x, y));
  5342. }
  5343. /**
  5344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5345. * Returns the updated Path2.
  5346. */
  5347. Path2.prototype.addLineTo = function (x, y) {
  5348. if (this.closed) {
  5349. //Tools.Error("cannot add lines to closed paths");
  5350. return this;
  5351. }
  5352. var newPoint = new Vector2(x, y);
  5353. var previousPoint = this._points[this._points.length - 1];
  5354. this._points.push(newPoint);
  5355. this._length += newPoint.subtract(previousPoint).length();
  5356. return this;
  5357. };
  5358. /**
  5359. * 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.
  5360. * Returns the updated Path2.
  5361. */
  5362. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5363. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5364. if (this.closed) {
  5365. //Tools.Error("cannot add arcs to closed paths");
  5366. return this;
  5367. }
  5368. var startPoint = this._points[this._points.length - 1];
  5369. var midPoint = new Vector2(midX, midY);
  5370. var endPoint = new Vector2(endX, endY);
  5371. var arc = new Arc2(startPoint, midPoint, endPoint);
  5372. var increment = arc.angle.radians() / numberOfSegments;
  5373. if (arc.orientation === Orientation.CW)
  5374. increment *= -1;
  5375. var currentAngle = arc.startAngle.radians() + increment;
  5376. for (var i = 0; i < numberOfSegments; i++) {
  5377. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5378. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5379. this.addLineTo(x, y);
  5380. currentAngle += increment;
  5381. }
  5382. return this;
  5383. };
  5384. /**
  5385. * Closes the Path2.
  5386. * Returns the Path2.
  5387. */
  5388. Path2.prototype.close = function () {
  5389. this.closed = true;
  5390. return this;
  5391. };
  5392. /**
  5393. * Returns the Path2 total length (float).
  5394. */
  5395. Path2.prototype.length = function () {
  5396. var result = this._length;
  5397. if (!this.closed) {
  5398. var lastPoint = this._points[this._points.length - 1];
  5399. var firstPoint = this._points[0];
  5400. result += (firstPoint.subtract(lastPoint).length());
  5401. }
  5402. return result;
  5403. };
  5404. /**
  5405. * Returns the Path2 internal array of points.
  5406. */
  5407. Path2.prototype.getPoints = function () {
  5408. return this._points;
  5409. };
  5410. /**
  5411. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5412. */
  5413. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5414. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5415. //Tools.Error("normalized length position should be between 0 and 1.");
  5416. return Vector2.Zero();
  5417. }
  5418. var lengthPosition = normalizedLengthPosition * this.length();
  5419. var previousOffset = 0;
  5420. for (var i = 0; i < this._points.length; i++) {
  5421. var j = (i + 1) % this._points.length;
  5422. var a = this._points[i];
  5423. var b = this._points[j];
  5424. var bToA = b.subtract(a);
  5425. var nextOffset = (bToA.length() + previousOffset);
  5426. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5427. var dir = bToA.normalize();
  5428. var localOffset = lengthPosition - previousOffset;
  5429. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5430. }
  5431. previousOffset = nextOffset;
  5432. }
  5433. //Tools.Error("internal error");
  5434. return Vector2.Zero();
  5435. };
  5436. /**
  5437. * Returns a new Path2 starting at the coordinates (x, y).
  5438. */
  5439. Path2.StartingAt = function (x, y) {
  5440. return new Path2(x, y);
  5441. };
  5442. return Path2;
  5443. }());
  5444. BABYLON.Path2 = Path2;
  5445. var Path3D = /** @class */ (function () {
  5446. /**
  5447. * new Path3D(path, normal, raw)
  5448. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5449. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5450. * path : an array of Vector3, the curve axis of the Path3D
  5451. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5452. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5453. */
  5454. function Path3D(path, firstNormal, raw) {
  5455. if (firstNormal === void 0) { firstNormal = null; }
  5456. this.path = path;
  5457. this._curve = new Array();
  5458. this._distances = new Array();
  5459. this._tangents = new Array();
  5460. this._normals = new Array();
  5461. this._binormals = new Array();
  5462. for (var p = 0; p < path.length; p++) {
  5463. this._curve[p] = path[p].clone(); // hard copy
  5464. }
  5465. this._raw = raw || false;
  5466. this._compute(firstNormal);
  5467. }
  5468. /**
  5469. * Returns the Path3D array of successive Vector3 designing its curve.
  5470. */
  5471. Path3D.prototype.getCurve = function () {
  5472. return this._curve;
  5473. };
  5474. /**
  5475. * Returns an array populated with tangent vectors on each Path3D curve point.
  5476. */
  5477. Path3D.prototype.getTangents = function () {
  5478. return this._tangents;
  5479. };
  5480. /**
  5481. * Returns an array populated with normal vectors on each Path3D curve point.
  5482. */
  5483. Path3D.prototype.getNormals = function () {
  5484. return this._normals;
  5485. };
  5486. /**
  5487. * Returns an array populated with binormal vectors on each Path3D curve point.
  5488. */
  5489. Path3D.prototype.getBinormals = function () {
  5490. return this._binormals;
  5491. };
  5492. /**
  5493. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5494. */
  5495. Path3D.prototype.getDistances = function () {
  5496. return this._distances;
  5497. };
  5498. /**
  5499. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5500. * Returns the same object updated.
  5501. */
  5502. Path3D.prototype.update = function (path, firstNormal) {
  5503. if (firstNormal === void 0) { firstNormal = null; }
  5504. for (var p = 0; p < path.length; p++) {
  5505. this._curve[p].x = path[p].x;
  5506. this._curve[p].y = path[p].y;
  5507. this._curve[p].z = path[p].z;
  5508. }
  5509. this._compute(firstNormal);
  5510. return this;
  5511. };
  5512. // private function compute() : computes tangents, normals and binormals
  5513. Path3D.prototype._compute = function (firstNormal) {
  5514. var l = this._curve.length;
  5515. // first and last tangents
  5516. this._tangents[0] = this._getFirstNonNullVector(0);
  5517. if (!this._raw) {
  5518. this._tangents[0].normalize();
  5519. }
  5520. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5521. if (!this._raw) {
  5522. this._tangents[l - 1].normalize();
  5523. }
  5524. // normals and binormals at first point : arbitrary vector with _normalVector()
  5525. var tg0 = this._tangents[0];
  5526. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5527. this._normals[0] = pp0;
  5528. if (!this._raw) {
  5529. this._normals[0].normalize();
  5530. }
  5531. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5532. if (!this._raw) {
  5533. this._binormals[0].normalize();
  5534. }
  5535. this._distances[0] = 0.0;
  5536. // normals and binormals : next points
  5537. var prev; // previous vector (segment)
  5538. var cur; // current vector (segment)
  5539. var curTang; // current tangent
  5540. // previous normal
  5541. var prevBinor; // previous binormal
  5542. for (var i = 1; i < l; i++) {
  5543. // tangents
  5544. prev = this._getLastNonNullVector(i);
  5545. if (i < l - 1) {
  5546. cur = this._getFirstNonNullVector(i);
  5547. this._tangents[i] = prev.add(cur);
  5548. this._tangents[i].normalize();
  5549. }
  5550. this._distances[i] = this._distances[i - 1] + prev.length();
  5551. // normals and binormals
  5552. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5553. curTang = this._tangents[i];
  5554. prevBinor = this._binormals[i - 1];
  5555. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5556. if (!this._raw) {
  5557. this._normals[i].normalize();
  5558. }
  5559. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5560. if (!this._raw) {
  5561. this._binormals[i].normalize();
  5562. }
  5563. }
  5564. };
  5565. // private function getFirstNonNullVector(index)
  5566. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5567. Path3D.prototype._getFirstNonNullVector = function (index) {
  5568. var i = 1;
  5569. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5570. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5571. i++;
  5572. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5573. }
  5574. return nNVector;
  5575. };
  5576. // private function getLastNonNullVector(index)
  5577. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5578. Path3D.prototype._getLastNonNullVector = function (index) {
  5579. var i = 1;
  5580. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5581. while (nLVector.length() === 0 && index > i + 1) {
  5582. i++;
  5583. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5584. }
  5585. return nLVector;
  5586. };
  5587. // private function normalVector(v0, vt, va) :
  5588. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5589. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5590. Path3D.prototype._normalVector = function (v0, vt, va) {
  5591. var normal0;
  5592. var tgl = vt.length();
  5593. if (tgl === 0.0) {
  5594. tgl = 1.0;
  5595. }
  5596. if (va === undefined || va === null) {
  5597. var point;
  5598. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5599. point = new Vector3(0.0, -1.0, 0.0);
  5600. }
  5601. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5602. point = new Vector3(1.0, 0.0, 0.0);
  5603. }
  5604. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5605. point = new Vector3(0.0, 0.0, 1.0);
  5606. }
  5607. else {
  5608. point = Vector3.Zero();
  5609. }
  5610. normal0 = Vector3.Cross(vt, point);
  5611. }
  5612. else {
  5613. normal0 = Vector3.Cross(vt, va);
  5614. Vector3.CrossToRef(normal0, vt, normal0);
  5615. }
  5616. normal0.normalize();
  5617. return normal0;
  5618. };
  5619. return Path3D;
  5620. }());
  5621. BABYLON.Path3D = Path3D;
  5622. var Curve3 = /** @class */ (function () {
  5623. /**
  5624. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5625. * A Curve3 is designed from a series of successive Vector3.
  5626. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5627. */
  5628. function Curve3(points) {
  5629. this._length = 0.0;
  5630. this._points = points;
  5631. this._length = this._computeLength(points);
  5632. }
  5633. /**
  5634. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5635. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5636. * @param v1 (Vector3) the control point
  5637. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5638. * @param nbPoints (integer) the wanted number of points in the curve
  5639. */
  5640. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5641. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5642. var bez = new Array();
  5643. var equation = function (t, val0, val1, val2) {
  5644. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5645. return res;
  5646. };
  5647. for (var i = 0; i <= nbPoints; i++) {
  5648. 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)));
  5649. }
  5650. return new Curve3(bez);
  5651. };
  5652. /**
  5653. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5654. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5655. * @param v1 (Vector3) the first control point
  5656. * @param v2 (Vector3) the second control point
  5657. * @param v3 (Vector3) the end point of the Cubic Bezier
  5658. * @param nbPoints (integer) the wanted number of points in the curve
  5659. */
  5660. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5661. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5662. var bez = new Array();
  5663. var equation = function (t, val0, val1, val2, val3) {
  5664. 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;
  5665. return res;
  5666. };
  5667. for (var i = 0; i <= nbPoints; i++) {
  5668. 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)));
  5669. }
  5670. return new Curve3(bez);
  5671. };
  5672. /**
  5673. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5674. * @param p1 (Vector3) the origin point of the Hermite Spline
  5675. * @param t1 (Vector3) the tangent vector at the origin point
  5676. * @param p2 (Vector3) the end point of the Hermite Spline
  5677. * @param t2 (Vector3) the tangent vector at the end point
  5678. * @param nbPoints (integer) the wanted number of points in the curve
  5679. */
  5680. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5681. var hermite = new Array();
  5682. var step = 1.0 / nbPoints;
  5683. for (var i = 0; i <= nbPoints; i++) {
  5684. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5685. }
  5686. return new Curve3(hermite);
  5687. };
  5688. /**
  5689. * Returns a Curve3 object along a CatmullRom Spline curve :
  5690. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5691. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5692. */
  5693. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5694. var totalPoints = new Array();
  5695. totalPoints.push(points[0].clone());
  5696. Array.prototype.push.apply(totalPoints, points);
  5697. totalPoints.push(points[points.length - 1].clone());
  5698. var catmullRom = new Array();
  5699. var step = 1.0 / nbPoints;
  5700. var amount = 0.0;
  5701. for (var i = 0; i < totalPoints.length - 3; i++) {
  5702. amount = 0;
  5703. for (var c = 0; c < nbPoints; c++) {
  5704. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5705. amount += step;
  5706. }
  5707. }
  5708. i--;
  5709. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5710. return new Curve3(catmullRom);
  5711. };
  5712. /**
  5713. * Returns the Curve3 stored array of successive Vector3
  5714. */
  5715. Curve3.prototype.getPoints = function () {
  5716. return this._points;
  5717. };
  5718. /**
  5719. * Returns the computed length (float) of the curve.
  5720. */
  5721. Curve3.prototype.length = function () {
  5722. return this._length;
  5723. };
  5724. /**
  5725. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5726. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5727. * curveA and curveB keep unchanged.
  5728. */
  5729. Curve3.prototype.continue = function (curve) {
  5730. var lastPoint = this._points[this._points.length - 1];
  5731. var continuedPoints = this._points.slice();
  5732. var curvePoints = curve.getPoints();
  5733. for (var i = 1; i < curvePoints.length; i++) {
  5734. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5735. }
  5736. var continuedCurve = new Curve3(continuedPoints);
  5737. return continuedCurve;
  5738. };
  5739. Curve3.prototype._computeLength = function (path) {
  5740. var l = 0;
  5741. for (var i = 1; i < path.length; i++) {
  5742. l += (path[i].subtract(path[i - 1])).length();
  5743. }
  5744. return l;
  5745. };
  5746. return Curve3;
  5747. }());
  5748. BABYLON.Curve3 = Curve3;
  5749. // Vertex formats
  5750. var PositionNormalVertex = /** @class */ (function () {
  5751. function PositionNormalVertex(position, normal) {
  5752. if (position === void 0) { position = Vector3.Zero(); }
  5753. if (normal === void 0) { normal = Vector3.Up(); }
  5754. this.position = position;
  5755. this.normal = normal;
  5756. }
  5757. PositionNormalVertex.prototype.clone = function () {
  5758. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5759. };
  5760. return PositionNormalVertex;
  5761. }());
  5762. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5763. var PositionNormalTextureVertex = /** @class */ (function () {
  5764. function PositionNormalTextureVertex(position, normal, uv) {
  5765. if (position === void 0) { position = Vector3.Zero(); }
  5766. if (normal === void 0) { normal = Vector3.Up(); }
  5767. if (uv === void 0) { uv = Vector2.Zero(); }
  5768. this.position = position;
  5769. this.normal = normal;
  5770. this.uv = uv;
  5771. }
  5772. PositionNormalTextureVertex.prototype.clone = function () {
  5773. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5774. };
  5775. return PositionNormalTextureVertex;
  5776. }());
  5777. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5778. // Temporary pre-allocated objects for engine internal use
  5779. // usage in any internal function :
  5780. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5781. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5782. var Tmp = /** @class */ (function () {
  5783. function Tmp() {
  5784. }
  5785. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5786. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5787. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5788. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5789. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5790. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5791. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5792. Matrix.Zero(), Matrix.Zero(),
  5793. Matrix.Zero(), Matrix.Zero(),
  5794. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5795. return Tmp;
  5796. }());
  5797. BABYLON.Tmp = Tmp;
  5798. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5799. var MathTmp = /** @class */ (function () {
  5800. function MathTmp() {
  5801. }
  5802. MathTmp.Vector3 = [Vector3.Zero()];
  5803. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5804. MathTmp.Quaternion = [Quaternion.Zero()];
  5805. return MathTmp;
  5806. }());
  5807. })(BABYLON || (BABYLON = {}));
  5808. //# sourceMappingURL=babylon.math.js.map
  5809. var BABYLON;
  5810. (function (BABYLON) {
  5811. var Scalar = /** @class */ (function () {
  5812. function Scalar() {
  5813. }
  5814. /**
  5815. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5816. */
  5817. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5818. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5819. var num = a - b;
  5820. return -epsilon <= num && num <= epsilon;
  5821. };
  5822. /**
  5823. * Returns a string : the upper case translation of the number i to hexadecimal.
  5824. */
  5825. Scalar.ToHex = function (i) {
  5826. var str = i.toString(16);
  5827. if (i <= 15) {
  5828. return ("0" + str).toUpperCase();
  5829. }
  5830. return str.toUpperCase();
  5831. };
  5832. /**
  5833. * Returns -1 if value is negative and +1 is value is positive.
  5834. * Returns the value itself if it's equal to zero.
  5835. */
  5836. Scalar.Sign = function (value) {
  5837. value = +value; // convert to a number
  5838. if (value === 0 || isNaN(value))
  5839. return value;
  5840. return value > 0 ? 1 : -1;
  5841. };
  5842. /**
  5843. * Returns the value itself if it's between min and max.
  5844. * Returns min if the value is lower than min.
  5845. * Returns max if the value is greater than max.
  5846. */
  5847. Scalar.Clamp = function (value, min, max) {
  5848. if (min === void 0) { min = 0; }
  5849. if (max === void 0) { max = 1; }
  5850. return Math.min(max, Math.max(min, value));
  5851. };
  5852. /**
  5853. * Returns the log2 of value.
  5854. */
  5855. Scalar.Log2 = function (value) {
  5856. return Math.log(value) * Math.LOG2E;
  5857. };
  5858. /**
  5859. * Loops the value, so that it is never larger than length and never smaller than 0.
  5860. *
  5861. * This is similar to the modulo operator but it works with floating point numbers.
  5862. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5863. * With t = 5 and length = 2.5, the result would be 0.0.
  5864. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5865. */
  5866. Scalar.Repeat = function (value, length) {
  5867. return value - Math.floor(value / length) * length;
  5868. };
  5869. /**
  5870. * Normalize the value between 0.0 and 1.0 using min and max values
  5871. */
  5872. Scalar.Normalize = function (value, min, max) {
  5873. return (value - min) / (max - min);
  5874. };
  5875. /**
  5876. * Denormalize the value from 0.0 and 1.0 using min and max values
  5877. */
  5878. Scalar.Denormalize = function (normalized, min, max) {
  5879. return (normalized * (max - min) + min);
  5880. };
  5881. /**
  5882. * Calculates the shortest difference between two given angles given in degrees.
  5883. */
  5884. Scalar.DeltaAngle = function (current, target) {
  5885. var num = Scalar.Repeat(target - current, 360.0);
  5886. if (num > 180.0) {
  5887. num -= 360.0;
  5888. }
  5889. return num;
  5890. };
  5891. /**
  5892. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5893. *
  5894. * The returned value will move back and forth between 0 and length
  5895. */
  5896. Scalar.PingPong = function (tx, length) {
  5897. var t = Scalar.Repeat(tx, length * 2.0);
  5898. return length - Math.abs(t - length);
  5899. };
  5900. /**
  5901. * Interpolates between min and max with smoothing at the limits.
  5902. *
  5903. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5904. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5905. */
  5906. Scalar.SmoothStep = function (from, to, tx) {
  5907. var t = Scalar.Clamp(tx);
  5908. t = -2.0 * t * t * t + 3.0 * t * t;
  5909. return to * t + from * (1.0 - t);
  5910. };
  5911. /**
  5912. * Moves a value current towards target.
  5913. *
  5914. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5915. * Negative values of maxDelta pushes the value away from target.
  5916. */
  5917. Scalar.MoveTowards = function (current, target, maxDelta) {
  5918. var result = 0;
  5919. if (Math.abs(target - current) <= maxDelta) {
  5920. result = target;
  5921. }
  5922. else {
  5923. result = current + Scalar.Sign(target - current) * maxDelta;
  5924. }
  5925. return result;
  5926. };
  5927. /**
  5928. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5929. *
  5930. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5931. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5932. */
  5933. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5934. var num = Scalar.DeltaAngle(current, target);
  5935. var result = 0;
  5936. if (-maxDelta < num && num < maxDelta) {
  5937. result = target;
  5938. }
  5939. else {
  5940. target = current + num;
  5941. result = Scalar.MoveTowards(current, target, maxDelta);
  5942. }
  5943. return result;
  5944. };
  5945. /**
  5946. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5947. */
  5948. Scalar.Lerp = function (start, end, amount) {
  5949. return start + ((end - start) * amount);
  5950. };
  5951. /**
  5952. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5953. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5954. */
  5955. Scalar.LerpAngle = function (start, end, amount) {
  5956. var num = Scalar.Repeat(end - start, 360.0);
  5957. if (num > 180.0) {
  5958. num -= 360.0;
  5959. }
  5960. return start + num * Scalar.Clamp(amount);
  5961. };
  5962. /**
  5963. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5964. */
  5965. Scalar.InverseLerp = function (a, b, value) {
  5966. var result = 0;
  5967. if (a != b) {
  5968. result = Scalar.Clamp((value - a) / (b - a));
  5969. }
  5970. else {
  5971. result = 0.0;
  5972. }
  5973. return result;
  5974. };
  5975. /**
  5976. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5977. */
  5978. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5979. var squared = amount * amount;
  5980. var cubed = amount * squared;
  5981. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5982. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5983. var part3 = (cubed - (2.0 * squared)) + amount;
  5984. var part4 = cubed - squared;
  5985. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5986. };
  5987. /**
  5988. * Returns a random float number between and min and max values
  5989. */
  5990. Scalar.RandomRange = function (min, max) {
  5991. if (min === max)
  5992. return min;
  5993. return ((Math.random() * (max - min)) + min);
  5994. };
  5995. /**
  5996. * This function returns percentage of a number in a given range.
  5997. *
  5998. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5999. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6000. */
  6001. Scalar.RangeToPercent = function (number, min, max) {
  6002. return ((number - min) / (max - min));
  6003. };
  6004. /**
  6005. * This function returns number that corresponds to the percentage in a given range.
  6006. *
  6007. * PercentToRange(0.34,0,100) will return 34.
  6008. */
  6009. Scalar.PercentToRange = function (percent, min, max) {
  6010. return ((max - min) * percent + min);
  6011. };
  6012. /**
  6013. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6014. * @param angle The angle to normalize in radian.
  6015. * @return The converted angle.
  6016. */
  6017. Scalar.NormalizeRadians = function (angle) {
  6018. // More precise but slower version kept for reference.
  6019. // angle = angle % Tools.TwoPi;
  6020. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6021. //if (angle > Math.PI) {
  6022. // angle -= Tools.TwoPi;
  6023. //}
  6024. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6025. return angle;
  6026. };
  6027. /**
  6028. * Two pi constants convenient for computation.
  6029. */
  6030. Scalar.TwoPi = Math.PI * 2;
  6031. return Scalar;
  6032. }());
  6033. BABYLON.Scalar = Scalar;
  6034. })(BABYLON || (BABYLON = {}));
  6035. //# sourceMappingURL=babylon.math.scalar.js.map
  6036. //# sourceMappingURL=babylon.mixins.js.map
  6037. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6038. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6039. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6040. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6041. //# sourceMappingURL=babylon.webgl2.js.map
  6042. var BABYLON;
  6043. (function (BABYLON) {
  6044. var __decoratorInitialStore = {};
  6045. var __mergedStore = {};
  6046. var _copySource = function (creationFunction, source, instanciate) {
  6047. var destination = creationFunction();
  6048. // Tags
  6049. if (BABYLON.Tags) {
  6050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6051. }
  6052. var classStore = getMergedStore(destination);
  6053. // Properties
  6054. for (var property in classStore) {
  6055. var propertyDescriptor = classStore[property];
  6056. var sourceProperty = source[property];
  6057. var propertyType = propertyDescriptor.type;
  6058. if (sourceProperty !== undefined && sourceProperty !== null) {
  6059. switch (propertyType) {
  6060. case 0: // Value
  6061. case 6:// Mesh reference
  6062. destination[property] = sourceProperty;
  6063. break;
  6064. case 1:// Texture
  6065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6066. break;
  6067. case 2: // Color3
  6068. case 3: // FresnelParameters
  6069. case 4: // Vector2
  6070. case 5: // Vector3
  6071. case 7: // Color Curves
  6072. case 10:// Quaternion
  6073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6074. break;
  6075. }
  6076. }
  6077. }
  6078. return destination;
  6079. };
  6080. function getDirectStore(target) {
  6081. var classKey = target.getClassName();
  6082. if (!__decoratorInitialStore[classKey]) {
  6083. __decoratorInitialStore[classKey] = {};
  6084. }
  6085. return __decoratorInitialStore[classKey];
  6086. }
  6087. /**
  6088. * Return the list of properties flagged as serializable
  6089. * @param target: host object
  6090. */
  6091. function getMergedStore(target) {
  6092. var classKey = target.getClassName();
  6093. if (__mergedStore[classKey]) {
  6094. return __mergedStore[classKey];
  6095. }
  6096. __mergedStore[classKey] = {};
  6097. var store = __mergedStore[classKey];
  6098. var currentTarget = target;
  6099. var currentKey = classKey;
  6100. while (currentKey) {
  6101. var initialStore = __decoratorInitialStore[currentKey];
  6102. for (var property in initialStore) {
  6103. store[property] = initialStore[property];
  6104. }
  6105. var parent_1 = void 0;
  6106. var done = false;
  6107. do {
  6108. parent_1 = Object.getPrototypeOf(currentTarget);
  6109. if (!parent_1.getClassName) {
  6110. done = true;
  6111. break;
  6112. }
  6113. if (parent_1.getClassName() !== currentKey) {
  6114. break;
  6115. }
  6116. currentTarget = parent_1;
  6117. } while (parent_1);
  6118. if (done) {
  6119. break;
  6120. }
  6121. currentKey = parent_1.getClassName();
  6122. currentTarget = parent_1;
  6123. }
  6124. return store;
  6125. }
  6126. function generateSerializableMember(type, sourceName) {
  6127. return function (target, propertyKey) {
  6128. var classStore = getDirectStore(target);
  6129. if (!classStore[propertyKey]) {
  6130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6131. }
  6132. };
  6133. }
  6134. function generateExpandMember(setCallback, targetKey) {
  6135. if (targetKey === void 0) { targetKey = null; }
  6136. return function (target, propertyKey) {
  6137. var key = targetKey || ("_" + propertyKey);
  6138. Object.defineProperty(target, propertyKey, {
  6139. get: function () {
  6140. return this[key];
  6141. },
  6142. set: function (value) {
  6143. if (this[key] === value) {
  6144. return;
  6145. }
  6146. this[key] = value;
  6147. target[setCallback].apply(this);
  6148. },
  6149. enumerable: true,
  6150. configurable: true
  6151. });
  6152. };
  6153. }
  6154. function expandToProperty(callback, targetKey) {
  6155. if (targetKey === void 0) { targetKey = null; }
  6156. return generateExpandMember(callback, targetKey);
  6157. }
  6158. BABYLON.expandToProperty = expandToProperty;
  6159. function serialize(sourceName) {
  6160. return generateSerializableMember(0, sourceName); // value member
  6161. }
  6162. BABYLON.serialize = serialize;
  6163. function serializeAsTexture(sourceName) {
  6164. return generateSerializableMember(1, sourceName); // texture member
  6165. }
  6166. BABYLON.serializeAsTexture = serializeAsTexture;
  6167. function serializeAsColor3(sourceName) {
  6168. return generateSerializableMember(2, sourceName); // color3 member
  6169. }
  6170. BABYLON.serializeAsColor3 = serializeAsColor3;
  6171. function serializeAsFresnelParameters(sourceName) {
  6172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6173. }
  6174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6175. function serializeAsVector2(sourceName) {
  6176. return generateSerializableMember(4, sourceName); // vector2 member
  6177. }
  6178. BABYLON.serializeAsVector2 = serializeAsVector2;
  6179. function serializeAsVector3(sourceName) {
  6180. return generateSerializableMember(5, sourceName); // vector3 member
  6181. }
  6182. BABYLON.serializeAsVector3 = serializeAsVector3;
  6183. function serializeAsMeshReference(sourceName) {
  6184. return generateSerializableMember(6, sourceName); // mesh reference member
  6185. }
  6186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6187. function serializeAsColorCurves(sourceName) {
  6188. return generateSerializableMember(7, sourceName); // color curves
  6189. }
  6190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6191. function serializeAsColor4(sourceName) {
  6192. return generateSerializableMember(8, sourceName); // color 4
  6193. }
  6194. BABYLON.serializeAsColor4 = serializeAsColor4;
  6195. function serializeAsImageProcessingConfiguration(sourceName) {
  6196. return generateSerializableMember(9, sourceName); // image processing
  6197. }
  6198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6199. function serializeAsQuaternion(sourceName) {
  6200. return generateSerializableMember(10, sourceName); // quaternion member
  6201. }
  6202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6203. var SerializationHelper = /** @class */ (function () {
  6204. function SerializationHelper() {
  6205. }
  6206. SerializationHelper.Serialize = function (entity, serializationObject) {
  6207. if (!serializationObject) {
  6208. serializationObject = {};
  6209. }
  6210. // Tags
  6211. if (BABYLON.Tags) {
  6212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6213. }
  6214. var serializedProperties = getMergedStore(entity);
  6215. // Properties
  6216. for (var property in serializedProperties) {
  6217. var propertyDescriptor = serializedProperties[property];
  6218. var targetPropertyName = propertyDescriptor.sourceName || property;
  6219. var propertyType = propertyDescriptor.type;
  6220. var sourceProperty = entity[property];
  6221. if (sourceProperty !== undefined && sourceProperty !== null) {
  6222. switch (propertyType) {
  6223. case 0:// Value
  6224. serializationObject[targetPropertyName] = sourceProperty;
  6225. break;
  6226. case 1:// Texture
  6227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6228. break;
  6229. case 2:// Color3
  6230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6231. break;
  6232. case 3:// FresnelParameters
  6233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6234. break;
  6235. case 4:// Vector2
  6236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6237. break;
  6238. case 5:// Vector3
  6239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6240. break;
  6241. case 6:// Mesh reference
  6242. serializationObject[targetPropertyName] = sourceProperty.id;
  6243. break;
  6244. case 7:// Color Curves
  6245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6246. break;
  6247. case 8:// Color 4
  6248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6249. break;
  6250. case 9:// Image Processing
  6251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6252. break;
  6253. }
  6254. }
  6255. }
  6256. return serializationObject;
  6257. };
  6258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6259. if (rootUrl === void 0) { rootUrl = null; }
  6260. var destination = creationFunction();
  6261. if (!rootUrl) {
  6262. rootUrl = "";
  6263. }
  6264. // Tags
  6265. if (BABYLON.Tags) {
  6266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6267. }
  6268. var classStore = getMergedStore(destination);
  6269. // Properties
  6270. for (var property in classStore) {
  6271. var propertyDescriptor = classStore[property];
  6272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6273. var propertyType = propertyDescriptor.type;
  6274. if (sourceProperty !== undefined && sourceProperty !== null) {
  6275. var dest = destination;
  6276. switch (propertyType) {
  6277. case 0:// Value
  6278. dest[property] = sourceProperty;
  6279. break;
  6280. case 1:// Texture
  6281. if (scene) {
  6282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6283. }
  6284. break;
  6285. case 2:// Color3
  6286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6287. break;
  6288. case 3:// FresnelParameters
  6289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6290. break;
  6291. case 4:// Vector2
  6292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6293. break;
  6294. case 5:// Vector3
  6295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6296. break;
  6297. case 6:// Mesh reference
  6298. if (scene) {
  6299. dest[property] = scene.getLastMeshByID(sourceProperty);
  6300. }
  6301. break;
  6302. case 7:// Color Curves
  6303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6304. break;
  6305. case 8:// Color 4
  6306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6307. break;
  6308. case 9:// Image Processing
  6309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6310. break;
  6311. }
  6312. }
  6313. }
  6314. return destination;
  6315. };
  6316. SerializationHelper.Clone = function (creationFunction, source) {
  6317. return _copySource(creationFunction, source, false);
  6318. };
  6319. SerializationHelper.Instanciate = function (creationFunction, source) {
  6320. return _copySource(creationFunction, source, true);
  6321. };
  6322. return SerializationHelper;
  6323. }());
  6324. BABYLON.SerializationHelper = SerializationHelper;
  6325. })(BABYLON || (BABYLON = {}));
  6326. //# sourceMappingURL=babylon.decorators.js.map
  6327. var BABYLON;
  6328. (function (BABYLON) {
  6329. /**
  6330. * A class serves as a medium between the observable and its observers
  6331. */
  6332. var EventState = /** @class */ (function () {
  6333. /**
  6334. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6335. */
  6336. function EventState(mask, skipNextObservers, target, currentTarget) {
  6337. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6338. this.initalize(mask, skipNextObservers, target, currentTarget);
  6339. }
  6340. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6341. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6342. this.mask = mask;
  6343. this.skipNextObservers = skipNextObservers;
  6344. this.target = target;
  6345. this.currentTarget = currentTarget;
  6346. return this;
  6347. };
  6348. return EventState;
  6349. }());
  6350. BABYLON.EventState = EventState;
  6351. /**
  6352. * Represent an Observer registered to a given Observable object.
  6353. */
  6354. var Observer = /** @class */ (function () {
  6355. function Observer(callback, mask, scope) {
  6356. if (scope === void 0) { scope = null; }
  6357. this.callback = callback;
  6358. this.mask = mask;
  6359. this.scope = scope;
  6360. }
  6361. return Observer;
  6362. }());
  6363. BABYLON.Observer = Observer;
  6364. /**
  6365. * Represent a list of observers registered to multiple Observables object.
  6366. */
  6367. var MultiObserver = /** @class */ (function () {
  6368. function MultiObserver() {
  6369. }
  6370. MultiObserver.prototype.dispose = function () {
  6371. if (this._observers && this._observables) {
  6372. for (var index = 0; index < this._observers.length; index++) {
  6373. this._observables[index].remove(this._observers[index]);
  6374. }
  6375. }
  6376. this._observers = null;
  6377. this._observables = null;
  6378. };
  6379. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6380. if (mask === void 0) { mask = -1; }
  6381. if (scope === void 0) { scope = null; }
  6382. var result = new MultiObserver();
  6383. result._observers = new Array();
  6384. result._observables = observables;
  6385. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6386. var observable = observables_1[_i];
  6387. var observer = observable.add(callback, mask, false, scope);
  6388. if (observer) {
  6389. result._observers.push(observer);
  6390. }
  6391. }
  6392. return result;
  6393. };
  6394. return MultiObserver;
  6395. }());
  6396. BABYLON.MultiObserver = MultiObserver;
  6397. /**
  6398. * The Observable class is a simple implementation of the Observable pattern.
  6399. * 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.
  6400. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6401. * 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).
  6402. * 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.
  6403. */
  6404. var Observable = /** @class */ (function () {
  6405. function Observable(onObserverAdded) {
  6406. this._observers = new Array();
  6407. this._eventState = new EventState(0);
  6408. if (onObserverAdded) {
  6409. this._onObserverAdded = onObserverAdded;
  6410. }
  6411. }
  6412. /**
  6413. * Create a new Observer with the specified callback
  6414. * @param callback the callback that will be executed for that Observer
  6415. * @param mask the mask used to filter observers
  6416. * @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.
  6417. * @param scope optional scope for the callback to be called from
  6418. */
  6419. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6420. if (mask === void 0) { mask = -1; }
  6421. if (insertFirst === void 0) { insertFirst = false; }
  6422. if (scope === void 0) { scope = null; }
  6423. if (!callback) {
  6424. return null;
  6425. }
  6426. var observer = new Observer(callback, mask, scope);
  6427. if (insertFirst) {
  6428. this._observers.unshift(observer);
  6429. }
  6430. else {
  6431. this._observers.push(observer);
  6432. }
  6433. if (this._onObserverAdded) {
  6434. this._onObserverAdded(observer);
  6435. }
  6436. return observer;
  6437. };
  6438. /**
  6439. * Remove an Observer from the Observable object
  6440. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6441. */
  6442. Observable.prototype.remove = function (observer) {
  6443. if (!observer) {
  6444. return false;
  6445. }
  6446. var index = this._observers.indexOf(observer);
  6447. if (index !== -1) {
  6448. this._observers.splice(index, 1);
  6449. return true;
  6450. }
  6451. return false;
  6452. };
  6453. /**
  6454. * Remove a callback from the Observable object
  6455. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6456. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6457. */
  6458. Observable.prototype.removeCallback = function (callback, scope) {
  6459. for (var index = 0; index < this._observers.length; index++) {
  6460. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6461. this._observers.splice(index, 1);
  6462. return true;
  6463. }
  6464. }
  6465. return false;
  6466. };
  6467. /**
  6468. * Notify all Observers by calling their respective callback with the given data
  6469. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6470. * @param eventData
  6471. * @param mask
  6472. */
  6473. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6474. if (mask === void 0) { mask = -1; }
  6475. if (!this._observers.length) {
  6476. return true;
  6477. }
  6478. var state = this._eventState;
  6479. state.mask = mask;
  6480. state.target = target;
  6481. state.currentTarget = currentTarget;
  6482. state.skipNextObservers = false;
  6483. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6484. var obs = _a[_i];
  6485. if (obs.mask & mask) {
  6486. if (obs.scope) {
  6487. obs.callback.apply(obs.scope, [eventData, state]);
  6488. }
  6489. else {
  6490. obs.callback(eventData, state);
  6491. }
  6492. }
  6493. if (state.skipNextObservers) {
  6494. return false;
  6495. }
  6496. }
  6497. return true;
  6498. };
  6499. /**
  6500. * Notify a specific observer
  6501. * @param eventData
  6502. * @param mask
  6503. */
  6504. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6505. if (mask === void 0) { mask = -1; }
  6506. var state = this._eventState;
  6507. state.mask = mask;
  6508. state.skipNextObservers = false;
  6509. observer.callback(eventData, state);
  6510. };
  6511. /**
  6512. * return true is the Observable has at least one Observer registered
  6513. */
  6514. Observable.prototype.hasObservers = function () {
  6515. return this._observers.length > 0;
  6516. };
  6517. /**
  6518. * Clear the list of observers
  6519. */
  6520. Observable.prototype.clear = function () {
  6521. this._observers = new Array();
  6522. this._onObserverAdded = null;
  6523. };
  6524. /**
  6525. * Clone the current observable
  6526. */
  6527. Observable.prototype.clone = function () {
  6528. var result = new Observable();
  6529. result._observers = this._observers.slice(0);
  6530. return result;
  6531. };
  6532. /**
  6533. * Does this observable handles observer registered with a given mask
  6534. * @param {number} trigger - the mask to be tested
  6535. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6536. **/
  6537. Observable.prototype.hasSpecificMask = function (mask) {
  6538. if (mask === void 0) { mask = -1; }
  6539. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6540. var obs = _a[_i];
  6541. if (obs.mask & mask || obs.mask === mask) {
  6542. return true;
  6543. }
  6544. }
  6545. return false;
  6546. };
  6547. return Observable;
  6548. }());
  6549. BABYLON.Observable = Observable;
  6550. })(BABYLON || (BABYLON = {}));
  6551. //# sourceMappingURL=babylon.observable.js.map
  6552. var BABYLON;
  6553. (function (BABYLON) {
  6554. var SmartArray = /** @class */ (function () {
  6555. function SmartArray(capacity) {
  6556. this.length = 0;
  6557. this.data = new Array(capacity);
  6558. this._id = SmartArray._GlobalId++;
  6559. }
  6560. SmartArray.prototype.push = function (value) {
  6561. this.data[this.length++] = value;
  6562. if (this.length > this.data.length) {
  6563. this.data.length *= 2;
  6564. }
  6565. };
  6566. SmartArray.prototype.forEach = function (func) {
  6567. for (var index = 0; index < this.length; index++) {
  6568. func(this.data[index]);
  6569. }
  6570. };
  6571. SmartArray.prototype.sort = function (compareFn) {
  6572. this.data.sort(compareFn);
  6573. };
  6574. SmartArray.prototype.reset = function () {
  6575. this.length = 0;
  6576. };
  6577. SmartArray.prototype.dispose = function () {
  6578. this.reset();
  6579. if (this.data) {
  6580. this.data.length = 0;
  6581. this.data = [];
  6582. }
  6583. };
  6584. SmartArray.prototype.concat = function (array) {
  6585. if (array.length === 0) {
  6586. return;
  6587. }
  6588. if (this.length + array.length > this.data.length) {
  6589. this.data.length = (this.length + array.length) * 2;
  6590. }
  6591. for (var index = 0; index < array.length; index++) {
  6592. this.data[this.length++] = (array.data || array)[index];
  6593. }
  6594. };
  6595. SmartArray.prototype.indexOf = function (value) {
  6596. var position = this.data.indexOf(value);
  6597. if (position >= this.length) {
  6598. return -1;
  6599. }
  6600. return position;
  6601. };
  6602. SmartArray.prototype.contains = function (value) {
  6603. return this.data.indexOf(value) !== -1;
  6604. };
  6605. // Statics
  6606. SmartArray._GlobalId = 0;
  6607. return SmartArray;
  6608. }());
  6609. BABYLON.SmartArray = SmartArray;
  6610. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6611. __extends(SmartArrayNoDuplicate, _super);
  6612. function SmartArrayNoDuplicate() {
  6613. var _this = _super !== null && _super.apply(this, arguments) || this;
  6614. _this._duplicateId = 0;
  6615. return _this;
  6616. }
  6617. SmartArrayNoDuplicate.prototype.push = function (value) {
  6618. _super.prototype.push.call(this, value);
  6619. if (!value.__smartArrayFlags) {
  6620. value.__smartArrayFlags = {};
  6621. }
  6622. value.__smartArrayFlags[this._id] = this._duplicateId;
  6623. };
  6624. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6625. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6626. return false;
  6627. }
  6628. this.push(value);
  6629. return true;
  6630. };
  6631. SmartArrayNoDuplicate.prototype.reset = function () {
  6632. _super.prototype.reset.call(this);
  6633. this._duplicateId++;
  6634. };
  6635. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6636. if (array.length === 0) {
  6637. return;
  6638. }
  6639. if (this.length + array.length > this.data.length) {
  6640. this.data.length = (this.length + array.length) * 2;
  6641. }
  6642. for (var index = 0; index < array.length; index++) {
  6643. var item = (array.data || array)[index];
  6644. this.pushNoDuplicate(item);
  6645. }
  6646. };
  6647. return SmartArrayNoDuplicate;
  6648. }(SmartArray));
  6649. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6650. })(BABYLON || (BABYLON = {}));
  6651. //# sourceMappingURL=babylon.smartArray.js.map
  6652. var BABYLON;
  6653. (function (BABYLON) {
  6654. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6655. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6656. var LoadFileError = /** @class */ (function (_super) {
  6657. __extends(LoadFileError, _super);
  6658. function LoadFileError(message, request) {
  6659. var _this = _super.call(this, message) || this;
  6660. _this.request = request;
  6661. _this.name = "LoadFileError";
  6662. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6663. return _this;
  6664. }
  6665. // Polyfill for Object.setPrototypeOf if necessary.
  6666. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6667. return LoadFileError;
  6668. }(Error));
  6669. BABYLON.LoadFileError = LoadFileError;
  6670. var RetryStrategy = /** @class */ (function () {
  6671. function RetryStrategy() {
  6672. }
  6673. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6674. if (maxRetries === void 0) { maxRetries = 3; }
  6675. if (baseInterval === void 0) { baseInterval = 500; }
  6676. return function (url, request, retryIndex) {
  6677. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6678. return -1;
  6679. }
  6680. return Math.pow(2, retryIndex) * baseInterval;
  6681. };
  6682. };
  6683. return RetryStrategy;
  6684. }());
  6685. BABYLON.RetryStrategy = RetryStrategy;
  6686. // Screenshots
  6687. var screenshotCanvas;
  6688. var cloneValue = function (source, destinationObject) {
  6689. if (!source)
  6690. return null;
  6691. if (source instanceof BABYLON.Mesh) {
  6692. return null;
  6693. }
  6694. if (source instanceof BABYLON.SubMesh) {
  6695. return source.clone(destinationObject);
  6696. }
  6697. else if (source.clone) {
  6698. return source.clone();
  6699. }
  6700. return null;
  6701. };
  6702. var Tools = /** @class */ (function () {
  6703. function Tools() {
  6704. }
  6705. /**
  6706. * Interpolates between a and b via alpha
  6707. * @param a The lower value (returned when alpha = 0)
  6708. * @param b The upper value (returned when alpha = 1)
  6709. * @param alpha The interpolation-factor
  6710. * @return The mixed value
  6711. */
  6712. Tools.Mix = function (a, b, alpha) {
  6713. return a * (1 - alpha) + b * alpha;
  6714. };
  6715. Tools.Instantiate = function (className) {
  6716. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6717. return Tools.RegisteredExternalClasses[className];
  6718. }
  6719. var arr = className.split(".");
  6720. var fn = (window || this);
  6721. for (var i = 0, len = arr.length; i < len; i++) {
  6722. fn = fn[arr[i]];
  6723. }
  6724. if (typeof fn !== "function") {
  6725. return null;
  6726. }
  6727. return fn;
  6728. };
  6729. Tools.SetImmediate = function (action) {
  6730. if (window.setImmediate) {
  6731. window.setImmediate(action);
  6732. }
  6733. else {
  6734. setTimeout(action, 1);
  6735. }
  6736. };
  6737. Tools.IsExponentOfTwo = function (value) {
  6738. var count = 1;
  6739. do {
  6740. count *= 2;
  6741. } while (count < value);
  6742. return count === value;
  6743. };
  6744. /**
  6745. * Find the next highest power of two.
  6746. * @param x Number to start search from.
  6747. * @return Next highest power of two.
  6748. */
  6749. Tools.CeilingPOT = function (x) {
  6750. x--;
  6751. x |= x >> 1;
  6752. x |= x >> 2;
  6753. x |= x >> 4;
  6754. x |= x >> 8;
  6755. x |= x >> 16;
  6756. x++;
  6757. return x;
  6758. };
  6759. /**
  6760. * Find the next lowest power of two.
  6761. * @param x Number to start search from.
  6762. * @return Next lowest power of two.
  6763. */
  6764. Tools.FloorPOT = function (x) {
  6765. x = x | (x >> 1);
  6766. x = x | (x >> 2);
  6767. x = x | (x >> 4);
  6768. x = x | (x >> 8);
  6769. x = x | (x >> 16);
  6770. return x - (x >> 1);
  6771. };
  6772. /**
  6773. * Find the nearest power of two.
  6774. * @param x Number to start search from.
  6775. * @return Next nearest power of two.
  6776. */
  6777. Tools.NearestPOT = function (x) {
  6778. var c = Tools.CeilingPOT(x);
  6779. var f = Tools.FloorPOT(x);
  6780. return (c - x) > (x - f) ? f : c;
  6781. };
  6782. Tools.GetExponentOfTwo = function (value, max, mode) {
  6783. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6784. var pot;
  6785. switch (mode) {
  6786. case BABYLON.Engine.SCALEMODE_FLOOR:
  6787. pot = Tools.FloorPOT(value);
  6788. break;
  6789. case BABYLON.Engine.SCALEMODE_NEAREST:
  6790. pot = Tools.NearestPOT(value);
  6791. break;
  6792. case BABYLON.Engine.SCALEMODE_CEILING:
  6793. default:
  6794. pot = Tools.CeilingPOT(value);
  6795. break;
  6796. }
  6797. return Math.min(pot, max);
  6798. };
  6799. Tools.GetFilename = function (path) {
  6800. var index = path.lastIndexOf("/");
  6801. if (index < 0)
  6802. return path;
  6803. return path.substring(index + 1);
  6804. };
  6805. Tools.GetFolderPath = function (uri) {
  6806. var index = uri.lastIndexOf("/");
  6807. if (index < 0)
  6808. return "";
  6809. return uri.substring(0, index + 1);
  6810. };
  6811. Tools.GetDOMTextContent = function (element) {
  6812. var result = "";
  6813. var child = element.firstChild;
  6814. while (child) {
  6815. if (child.nodeType === 3) {
  6816. result += child.textContent;
  6817. }
  6818. child = child.nextSibling;
  6819. }
  6820. return result;
  6821. };
  6822. Tools.ToDegrees = function (angle) {
  6823. return angle * 180 / Math.PI;
  6824. };
  6825. Tools.ToRadians = function (angle) {
  6826. return angle * Math.PI / 180;
  6827. };
  6828. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6829. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6830. var output = "";
  6831. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6832. var i = 0;
  6833. var bytes = new Uint8Array(buffer);
  6834. while (i < bytes.length) {
  6835. chr1 = bytes[i++];
  6836. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6837. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6838. enc1 = chr1 >> 2;
  6839. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6840. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6841. enc4 = chr3 & 63;
  6842. if (isNaN(chr2)) {
  6843. enc3 = enc4 = 64;
  6844. }
  6845. else if (isNaN(chr3)) {
  6846. enc4 = 64;
  6847. }
  6848. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6849. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6850. }
  6851. return "data:image/png;base64," + output;
  6852. };
  6853. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6854. if (bias === void 0) { bias = null; }
  6855. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6856. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6857. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6858. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6859. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6860. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6861. }
  6862. if (bias) {
  6863. minimum.x -= minimum.x * bias.x + bias.y;
  6864. minimum.y -= minimum.y * bias.x + bias.y;
  6865. minimum.z -= minimum.z * bias.x + bias.y;
  6866. maximum.x += maximum.x * bias.x + bias.y;
  6867. maximum.y += maximum.y * bias.x + bias.y;
  6868. maximum.z += maximum.z * bias.x + bias.y;
  6869. }
  6870. return {
  6871. minimum: minimum,
  6872. maximum: maximum
  6873. };
  6874. };
  6875. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6876. if (bias === void 0) { bias = null; }
  6877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6879. if (!stride) {
  6880. stride = 3;
  6881. }
  6882. for (var index = start; index < start + count; index++) {
  6883. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6886. }
  6887. if (bias) {
  6888. minimum.x -= minimum.x * bias.x + bias.y;
  6889. minimum.y -= minimum.y * bias.x + bias.y;
  6890. minimum.z -= minimum.z * bias.x + bias.y;
  6891. maximum.x += maximum.x * bias.x + bias.y;
  6892. maximum.y += maximum.y * bias.x + bias.y;
  6893. maximum.z += maximum.z * bias.x + bias.y;
  6894. }
  6895. return {
  6896. minimum: minimum,
  6897. maximum: maximum
  6898. };
  6899. };
  6900. Tools.Vector2ArrayFeeder = function (array) {
  6901. return function (index) {
  6902. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6903. var length = isFloatArray ? array.length / 2 : array.length;
  6904. if (index >= length) {
  6905. return null;
  6906. }
  6907. if (isFloatArray) {
  6908. var fa = array;
  6909. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6910. }
  6911. var a = array;
  6912. return a[index];
  6913. };
  6914. };
  6915. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6916. if (bias === void 0) { bias = null; }
  6917. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6918. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6919. var i = 0;
  6920. var cur = feeder(i++);
  6921. while (cur) {
  6922. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6923. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6924. cur = feeder(i++);
  6925. }
  6926. if (bias) {
  6927. minimum.x -= minimum.x * bias.x + bias.y;
  6928. minimum.y -= minimum.y * bias.x + bias.y;
  6929. maximum.x += maximum.x * bias.x + bias.y;
  6930. maximum.y += maximum.y * bias.x + bias.y;
  6931. }
  6932. return {
  6933. minimum: minimum,
  6934. maximum: maximum
  6935. };
  6936. };
  6937. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6938. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6939. return null;
  6940. return Array.isArray(obj) ? obj : [obj];
  6941. };
  6942. // Misc.
  6943. Tools.GetPointerPrefix = function () {
  6944. var eventPrefix = "pointer";
  6945. // Check if pointer events are supported
  6946. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6947. eventPrefix = "mouse";
  6948. }
  6949. return eventPrefix;
  6950. };
  6951. /**
  6952. * @param func - the function to be called
  6953. * @param requester - the object that will request the next frame. Falls back to window.
  6954. */
  6955. Tools.QueueNewFrame = function (func, requester) {
  6956. if (!Tools.IsWindowObjectExist()) {
  6957. return setTimeout(func, 16);
  6958. }
  6959. if (!requester) {
  6960. requester = window;
  6961. }
  6962. if (requester.requestAnimationFrame) {
  6963. return requester.requestAnimationFrame(func);
  6964. }
  6965. else if (requester.msRequestAnimationFrame) {
  6966. return requester.msRequestAnimationFrame(func);
  6967. }
  6968. else if (requester.webkitRequestAnimationFrame) {
  6969. return requester.webkitRequestAnimationFrame(func);
  6970. }
  6971. else if (requester.mozRequestAnimationFrame) {
  6972. return requester.mozRequestAnimationFrame(func);
  6973. }
  6974. else if (requester.oRequestAnimationFrame) {
  6975. return requester.oRequestAnimationFrame(func);
  6976. }
  6977. else {
  6978. return window.setTimeout(func, 16);
  6979. }
  6980. };
  6981. Tools.RequestFullscreen = function (element) {
  6982. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6983. if (!requestFunction)
  6984. return;
  6985. requestFunction.call(element);
  6986. };
  6987. Tools.ExitFullscreen = function () {
  6988. if (document.exitFullscreen) {
  6989. document.exitFullscreen();
  6990. }
  6991. else if (document.mozCancelFullScreen) {
  6992. document.mozCancelFullScreen();
  6993. }
  6994. else if (document.webkitCancelFullScreen) {
  6995. document.webkitCancelFullScreen();
  6996. }
  6997. else if (document.msCancelFullScreen) {
  6998. document.msCancelFullScreen();
  6999. }
  7000. };
  7001. Tools.SetCorsBehavior = function (url, element) {
  7002. if (url && url.indexOf("data:") === 0) {
  7003. return;
  7004. }
  7005. if (Tools.CorsBehavior) {
  7006. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7007. element.crossOrigin = Tools.CorsBehavior;
  7008. }
  7009. else {
  7010. var result = Tools.CorsBehavior(url);
  7011. if (result) {
  7012. element.crossOrigin = result;
  7013. }
  7014. }
  7015. }
  7016. };
  7017. // External files
  7018. Tools.CleanUrl = function (url) {
  7019. url = url.replace(/#/mg, "%23");
  7020. return url;
  7021. };
  7022. Tools.LoadImage = function (url, onLoad, onError, database) {
  7023. if (url instanceof ArrayBuffer) {
  7024. url = Tools.EncodeArrayBufferTobase64(url);
  7025. }
  7026. url = Tools.CleanUrl(url);
  7027. url = Tools.PreprocessUrl(url);
  7028. var img = new Image();
  7029. Tools.SetCorsBehavior(url, img);
  7030. img.onload = function () {
  7031. onLoad(img);
  7032. };
  7033. img.onerror = function (err) {
  7034. Tools.Error("Error while trying to load image: " + url);
  7035. if (onError) {
  7036. onError("Error while trying to load image: " + url, err);
  7037. }
  7038. };
  7039. var noIndexedDB = function () {
  7040. img.src = url;
  7041. };
  7042. var loadFromIndexedDB = function () {
  7043. if (database) {
  7044. database.loadImageFromDB(url, img);
  7045. }
  7046. };
  7047. //ANY database to do!
  7048. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7049. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7050. }
  7051. else {
  7052. if (url.indexOf("file:") !== -1) {
  7053. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7054. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7055. try {
  7056. var blobURL;
  7057. try {
  7058. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7059. }
  7060. catch (ex) {
  7061. // Chrome doesn't support oneTimeOnly parameter
  7062. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7063. }
  7064. img.src = blobURL;
  7065. }
  7066. catch (e) {
  7067. img.src = "";
  7068. }
  7069. return img;
  7070. }
  7071. }
  7072. noIndexedDB();
  7073. }
  7074. return img;
  7075. };
  7076. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7077. url = Tools.CleanUrl(url);
  7078. url = Tools.PreprocessUrl(url);
  7079. // If file and file input are set
  7080. if (url.indexOf("file:") !== -1) {
  7081. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7082. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7083. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7084. }
  7085. }
  7086. var loadUrl = Tools.BaseUrl + url;
  7087. var aborted = false;
  7088. var fileRequest = {
  7089. onCompleteObservable: new BABYLON.Observable(),
  7090. abort: function () { return aborted = true; },
  7091. };
  7092. var requestFile = function () {
  7093. var request = new XMLHttpRequest();
  7094. var retryHandle = null;
  7095. fileRequest.abort = function () {
  7096. aborted = true;
  7097. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7098. request.abort();
  7099. }
  7100. if (retryHandle !== null) {
  7101. clearTimeout(retryHandle);
  7102. retryHandle = null;
  7103. }
  7104. };
  7105. var retryLoop = function (retryIndex) {
  7106. request.open('GET', loadUrl, true);
  7107. if (useArrayBuffer) {
  7108. request.responseType = "arraybuffer";
  7109. }
  7110. if (onProgress) {
  7111. request.addEventListener("progress", onProgress);
  7112. }
  7113. var onLoadEnd = function () {
  7114. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7115. };
  7116. request.addEventListener("loadend", onLoadEnd);
  7117. var onReadyStateChange = function () {
  7118. if (aborted) {
  7119. return;
  7120. }
  7121. // In case of undefined state in some browsers.
  7122. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7123. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7124. request.removeEventListener("readystatechange", onReadyStateChange);
  7125. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7126. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7127. return;
  7128. }
  7129. var retryStrategy = Tools.DefaultRetryStrategy;
  7130. if (retryStrategy) {
  7131. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7132. if (waitTime !== -1) {
  7133. // Prevent the request from completing for retry.
  7134. request.removeEventListener("loadend", onLoadEnd);
  7135. request = new XMLHttpRequest();
  7136. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7137. return;
  7138. }
  7139. }
  7140. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7141. if (onError) {
  7142. onError(request, e);
  7143. }
  7144. else {
  7145. throw e;
  7146. }
  7147. }
  7148. };
  7149. request.addEventListener("readystatechange", onReadyStateChange);
  7150. request.send();
  7151. };
  7152. retryLoop(0);
  7153. };
  7154. // Caching all files
  7155. if (database && database.enableSceneOffline) {
  7156. var noIndexedDB_1 = function () {
  7157. if (!aborted) {
  7158. requestFile();
  7159. }
  7160. };
  7161. var loadFromIndexedDB = function () {
  7162. // TODO: database needs to support aborting and should return a IFileRequest
  7163. if (aborted) {
  7164. return;
  7165. }
  7166. if (database) {
  7167. database.loadFileFromDB(url, function (data) {
  7168. if (!aborted) {
  7169. onSuccess(data);
  7170. }
  7171. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7172. }, onProgress ? function (event) {
  7173. if (!aborted) {
  7174. onProgress(event);
  7175. }
  7176. } : undefined, noIndexedDB_1, useArrayBuffer);
  7177. }
  7178. };
  7179. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7180. }
  7181. else {
  7182. requestFile();
  7183. }
  7184. return fileRequest;
  7185. };
  7186. /**
  7187. * Load a script (identified by an url). When the url returns, the
  7188. * content of this file is added into a new script element, attached to the DOM (body element)
  7189. */
  7190. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7191. var head = document.getElementsByTagName('head')[0];
  7192. var script = document.createElement('script');
  7193. script.type = 'text/javascript';
  7194. script.src = scriptUrl;
  7195. script.onload = function () {
  7196. if (onSuccess) {
  7197. onSuccess();
  7198. }
  7199. };
  7200. script.onerror = function (e) {
  7201. if (onError) {
  7202. onError("Unable to load script", e);
  7203. }
  7204. };
  7205. head.appendChild(script);
  7206. };
  7207. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7208. var reader = new FileReader();
  7209. var request = {
  7210. onCompleteObservable: new BABYLON.Observable(),
  7211. abort: function () { return reader.abort(); },
  7212. };
  7213. reader.onloadend = function (e) {
  7214. request.onCompleteObservable.notifyObservers(request);
  7215. };
  7216. reader.onload = function (e) {
  7217. //target doesn't have result from ts 1.3
  7218. callback(e.target['result']);
  7219. };
  7220. reader.onprogress = progressCallback;
  7221. reader.readAsDataURL(fileToLoad);
  7222. return request;
  7223. };
  7224. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7225. var reader = new FileReader();
  7226. var request = {
  7227. onCompleteObservable: new BABYLON.Observable(),
  7228. abort: function () { return reader.abort(); },
  7229. };
  7230. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7231. reader.onerror = function (e) {
  7232. Tools.Log("Error while reading file: " + fileToLoad.name);
  7233. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7234. };
  7235. reader.onload = function (e) {
  7236. //target doesn't have result from ts 1.3
  7237. callback(e.target['result']);
  7238. };
  7239. if (progressCallBack) {
  7240. reader.onprogress = progressCallBack;
  7241. }
  7242. if (!useArrayBuffer) {
  7243. // Asynchronous read
  7244. reader.readAsText(fileToLoad);
  7245. }
  7246. else {
  7247. reader.readAsArrayBuffer(fileToLoad);
  7248. }
  7249. return request;
  7250. };
  7251. //returns a downloadable url to a file content.
  7252. Tools.FileAsURL = function (content) {
  7253. var fileBlob = new Blob([content]);
  7254. var url = window.URL || window.webkitURL;
  7255. var link = url.createObjectURL(fileBlob);
  7256. return link;
  7257. };
  7258. // Misc.
  7259. Tools.Format = function (value, decimals) {
  7260. if (decimals === void 0) { decimals = 2; }
  7261. return value.toFixed(decimals);
  7262. };
  7263. Tools.CheckExtends = function (v, min, max) {
  7264. if (v.x < min.x)
  7265. min.x = v.x;
  7266. if (v.y < min.y)
  7267. min.y = v.y;
  7268. if (v.z < min.z)
  7269. min.z = v.z;
  7270. if (v.x > max.x)
  7271. max.x = v.x;
  7272. if (v.y > max.y)
  7273. max.y = v.y;
  7274. if (v.z > max.z)
  7275. max.z = v.z;
  7276. };
  7277. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7278. for (var prop in source) {
  7279. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7280. continue;
  7281. }
  7282. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7283. continue;
  7284. }
  7285. var sourceValue = source[prop];
  7286. var typeOfSourceValue = typeof sourceValue;
  7287. if (typeOfSourceValue === "function") {
  7288. continue;
  7289. }
  7290. if (typeOfSourceValue === "object") {
  7291. if (sourceValue instanceof Array) {
  7292. destination[prop] = [];
  7293. if (sourceValue.length > 0) {
  7294. if (typeof sourceValue[0] == "object") {
  7295. for (var index = 0; index < sourceValue.length; index++) {
  7296. var clonedValue = cloneValue(sourceValue[index], destination);
  7297. if (destination[prop].indexOf(clonedValue) === -1) {
  7298. destination[prop].push(clonedValue);
  7299. }
  7300. }
  7301. }
  7302. else {
  7303. destination[prop] = sourceValue.slice(0);
  7304. }
  7305. }
  7306. }
  7307. else {
  7308. destination[prop] = cloneValue(sourceValue, destination);
  7309. }
  7310. }
  7311. else {
  7312. destination[prop] = sourceValue;
  7313. }
  7314. }
  7315. };
  7316. Tools.IsEmpty = function (obj) {
  7317. for (var i in obj) {
  7318. if (obj.hasOwnProperty(i)) {
  7319. return false;
  7320. }
  7321. }
  7322. return true;
  7323. };
  7324. Tools.RegisterTopRootEvents = function (events) {
  7325. for (var index = 0; index < events.length; index++) {
  7326. var event = events[index];
  7327. window.addEventListener(event.name, event.handler, false);
  7328. try {
  7329. if (window.parent) {
  7330. window.parent.addEventListener(event.name, event.handler, false);
  7331. }
  7332. }
  7333. catch (e) {
  7334. // Silently fails...
  7335. }
  7336. }
  7337. };
  7338. Tools.UnregisterTopRootEvents = function (events) {
  7339. for (var index = 0; index < events.length; index++) {
  7340. var event = events[index];
  7341. window.removeEventListener(event.name, event.handler);
  7342. try {
  7343. if (window.parent) {
  7344. window.parent.removeEventListener(event.name, event.handler);
  7345. }
  7346. }
  7347. catch (e) {
  7348. // Silently fails...
  7349. }
  7350. }
  7351. };
  7352. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7353. if (mimeType === void 0) { mimeType = "image/png"; }
  7354. // Read the contents of the framebuffer
  7355. var numberOfChannelsByLine = width * 4;
  7356. var halfHeight = height / 2;
  7357. //Reading datas from WebGL
  7358. var data = engine.readPixels(0, 0, width, height);
  7359. //To flip image on Y axis.
  7360. for (var i = 0; i < halfHeight; i++) {
  7361. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7362. var currentCell = j + i * numberOfChannelsByLine;
  7363. var targetLine = height - i - 1;
  7364. var targetCell = j + targetLine * numberOfChannelsByLine;
  7365. var temp = data[currentCell];
  7366. data[currentCell] = data[targetCell];
  7367. data[targetCell] = temp;
  7368. }
  7369. }
  7370. // Create a 2D canvas to store the result
  7371. if (!screenshotCanvas) {
  7372. screenshotCanvas = document.createElement('canvas');
  7373. }
  7374. screenshotCanvas.width = width;
  7375. screenshotCanvas.height = height;
  7376. var context = screenshotCanvas.getContext('2d');
  7377. if (context) {
  7378. // Copy the pixels to a 2D canvas
  7379. var imageData = context.createImageData(width, height);
  7380. var castData = (imageData.data);
  7381. castData.set(data);
  7382. context.putImageData(imageData, 0, 0);
  7383. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7384. }
  7385. };
  7386. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7387. if (mimeType === void 0) { mimeType = "image/png"; }
  7388. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7389. if (successCallback) {
  7390. successCallback(base64Image);
  7391. }
  7392. else {
  7393. // We need HTMLCanvasElement.toBlob for HD screenshots
  7394. if (!screenshotCanvas.toBlob) {
  7395. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7396. screenshotCanvas.toBlob = function (callback, type, quality) {
  7397. var _this = this;
  7398. setTimeout(function () {
  7399. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7400. for (var i = 0; i < len; i++) {
  7401. arr[i] = binStr.charCodeAt(i);
  7402. }
  7403. callback(new Blob([arr], { type: type || 'image/png' }));
  7404. });
  7405. };
  7406. }
  7407. screenshotCanvas.toBlob(function (blob) {
  7408. var url = URL.createObjectURL(blob);
  7409. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7410. if (("download" in document.createElement("a"))) {
  7411. var a = window.document.createElement("a");
  7412. a.href = url;
  7413. if (fileName) {
  7414. a.setAttribute("download", fileName);
  7415. }
  7416. else {
  7417. var date = new Date();
  7418. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7419. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7420. }
  7421. window.document.body.appendChild(a);
  7422. a.addEventListener("click", function () {
  7423. if (a.parentElement) {
  7424. a.parentElement.removeChild(a);
  7425. }
  7426. });
  7427. a.click();
  7428. }
  7429. else {
  7430. var newWindow = window.open("");
  7431. if (!newWindow)
  7432. return;
  7433. var img = newWindow.document.createElement("img");
  7434. img.onload = function () {
  7435. // no longer need to read the blob so it's revoked
  7436. URL.revokeObjectURL(url);
  7437. };
  7438. img.src = url;
  7439. newWindow.document.body.appendChild(img);
  7440. }
  7441. });
  7442. }
  7443. };
  7444. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7445. if (mimeType === void 0) { mimeType = "image/png"; }
  7446. var width;
  7447. var height;
  7448. // If a precision value is specified
  7449. if (size.precision) {
  7450. width = Math.round(engine.getRenderWidth() * size.precision);
  7451. height = Math.round(width / engine.getAspectRatio(camera));
  7452. }
  7453. else if (size.width && size.height) {
  7454. width = size.width;
  7455. height = size.height;
  7456. }
  7457. else if (size.width && !size.height) {
  7458. width = size.width;
  7459. height = Math.round(width / engine.getAspectRatio(camera));
  7460. }
  7461. else if (size.height && !size.width) {
  7462. height = size.height;
  7463. width = Math.round(height * engine.getAspectRatio(camera));
  7464. }
  7465. else if (!isNaN(size)) {
  7466. height = size;
  7467. width = size;
  7468. }
  7469. else {
  7470. Tools.Error("Invalid 'size' parameter !");
  7471. return;
  7472. }
  7473. if (!screenshotCanvas) {
  7474. screenshotCanvas = document.createElement('canvas');
  7475. }
  7476. screenshotCanvas.width = width;
  7477. screenshotCanvas.height = height;
  7478. var renderContext = screenshotCanvas.getContext("2d");
  7479. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7480. var newWidth = width;
  7481. var newHeight = newWidth / ratio;
  7482. if (newHeight > height) {
  7483. newHeight = height;
  7484. newWidth = newHeight * ratio;
  7485. }
  7486. var offsetX = Math.max(0, width - newWidth) / 2;
  7487. var offsetY = Math.max(0, height - newHeight) / 2;
  7488. var renderingCanvas = engine.getRenderingCanvas();
  7489. if (renderContext && renderingCanvas) {
  7490. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7491. }
  7492. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7493. };
  7494. /**
  7495. * Generates an image screenshot from the specified camera.
  7496. *
  7497. * @param engine The engine to use for rendering
  7498. * @param camera The camera to use for rendering
  7499. * @param size This parameter can be set to a single number or to an object with the
  7500. * following (optional) properties: precision, width, height. If a single number is passed,
  7501. * it will be used for both width and height. If an object is passed, the screenshot size
  7502. * will be derived from the parameters. The precision property is a multiplier allowing
  7503. * rendering at a higher or lower resolution.
  7504. * @param successCallback The callback receives a single parameter which contains the
  7505. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7506. * src parameter of an <img> to display it.
  7507. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7508. * Check your browser for supported MIME types.
  7509. * @param samples Texture samples (default: 1)
  7510. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7511. * @param fileName A name for for the downloaded file.
  7512. * @constructor
  7513. */
  7514. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7515. if (mimeType === void 0) { mimeType = "image/png"; }
  7516. if (samples === void 0) { samples = 1; }
  7517. if (antialiasing === void 0) { antialiasing = false; }
  7518. var width;
  7519. var height;
  7520. //If a precision value is specified
  7521. if (size.precision) {
  7522. width = Math.round(engine.getRenderWidth() * size.precision);
  7523. height = Math.round(width / engine.getAspectRatio(camera));
  7524. size = { width: width, height: height };
  7525. }
  7526. else if (size.width && size.height) {
  7527. width = size.width;
  7528. height = size.height;
  7529. }
  7530. else if (size.width && !size.height) {
  7531. width = size.width;
  7532. height = Math.round(width / engine.getAspectRatio(camera));
  7533. size = { width: width, height: height };
  7534. }
  7535. else if (size.height && !size.width) {
  7536. height = size.height;
  7537. width = Math.round(height * engine.getAspectRatio(camera));
  7538. size = { width: width, height: height };
  7539. }
  7540. else if (!isNaN(size)) {
  7541. height = size;
  7542. width = size;
  7543. }
  7544. else {
  7545. Tools.Error("Invalid 'size' parameter !");
  7546. return;
  7547. }
  7548. var scene = camera.getScene();
  7549. var previousCamera = null;
  7550. if (scene.activeCamera !== camera) {
  7551. previousCamera = scene.activeCamera;
  7552. scene.activeCamera = camera;
  7553. }
  7554. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7555. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7556. texture.renderList = null;
  7557. texture.samples = samples;
  7558. if (antialiasing) {
  7559. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7560. }
  7561. texture.onAfterRenderObservable.add(function () {
  7562. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7563. });
  7564. scene.incrementRenderId();
  7565. scene.resetCachedMaterial();
  7566. texture.render(true);
  7567. texture.dispose();
  7568. if (previousCamera) {
  7569. scene.activeCamera = previousCamera;
  7570. }
  7571. camera.getProjectionMatrix(true); // Force cache refresh;
  7572. };
  7573. // XHR response validator for local file scenario
  7574. Tools.ValidateXHRData = function (xhr, dataType) {
  7575. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7576. if (dataType === void 0) { dataType = 7; }
  7577. try {
  7578. if (dataType & 1) {
  7579. if (xhr.responseText && xhr.responseText.length > 0) {
  7580. return true;
  7581. }
  7582. else if (dataType === 1) {
  7583. return false;
  7584. }
  7585. }
  7586. if (dataType & 2) {
  7587. // Check header width and height since there is no "TGA" magic number
  7588. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7589. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7590. return true;
  7591. }
  7592. else if (dataType === 2) {
  7593. return false;
  7594. }
  7595. }
  7596. if (dataType & 4) {
  7597. // Check for the "DDS" magic number
  7598. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7599. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7600. return true;
  7601. }
  7602. else {
  7603. return false;
  7604. }
  7605. }
  7606. }
  7607. catch (e) {
  7608. // Global protection
  7609. }
  7610. return false;
  7611. };
  7612. /**
  7613. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7614. * Be aware Math.random() could cause collisions, but:
  7615. * "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"
  7616. */
  7617. Tools.RandomId = function () {
  7618. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7619. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7620. return v.toString(16);
  7621. });
  7622. };
  7623. Object.defineProperty(Tools, "NoneLogLevel", {
  7624. get: function () {
  7625. return Tools._NoneLogLevel;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(Tools, "MessageLogLevel", {
  7631. get: function () {
  7632. return Tools._MessageLogLevel;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(Tools, "WarningLogLevel", {
  7638. get: function () {
  7639. return Tools._WarningLogLevel;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(Tools, "ErrorLogLevel", {
  7645. get: function () {
  7646. return Tools._ErrorLogLevel;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Tools, "AllLogLevel", {
  7652. get: function () {
  7653. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Tools._AddLogEntry = function (entry) {
  7659. Tools._LogCache = entry + Tools._LogCache;
  7660. if (Tools.OnNewCacheEntry) {
  7661. Tools.OnNewCacheEntry(entry);
  7662. }
  7663. };
  7664. Tools._FormatMessage = function (message) {
  7665. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7666. var date = new Date();
  7667. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7668. };
  7669. Tools._LogDisabled = function (message) {
  7670. // nothing to do
  7671. };
  7672. Tools._LogEnabled = function (message) {
  7673. var formattedMessage = Tools._FormatMessage(message);
  7674. console.log("BJS - " + formattedMessage);
  7675. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7676. Tools._AddLogEntry(entry);
  7677. };
  7678. Tools._WarnDisabled = function (message) {
  7679. // nothing to do
  7680. };
  7681. Tools._WarnEnabled = function (message) {
  7682. var formattedMessage = Tools._FormatMessage(message);
  7683. console.warn("BJS - " + formattedMessage);
  7684. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7685. Tools._AddLogEntry(entry);
  7686. };
  7687. Tools._ErrorDisabled = function (message) {
  7688. // nothing to do
  7689. };
  7690. Tools._ErrorEnabled = function (message) {
  7691. Tools.errorsCount++;
  7692. var formattedMessage = Tools._FormatMessage(message);
  7693. console.error("BJS - " + formattedMessage);
  7694. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7695. Tools._AddLogEntry(entry);
  7696. };
  7697. Object.defineProperty(Tools, "LogCache", {
  7698. get: function () {
  7699. return Tools._LogCache;
  7700. },
  7701. enumerable: true,
  7702. configurable: true
  7703. });
  7704. Tools.ClearLogCache = function () {
  7705. Tools._LogCache = "";
  7706. Tools.errorsCount = 0;
  7707. };
  7708. Object.defineProperty(Tools, "LogLevels", {
  7709. set: function (level) {
  7710. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7711. Tools.Log = Tools._LogEnabled;
  7712. }
  7713. else {
  7714. Tools.Log = Tools._LogDisabled;
  7715. }
  7716. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7717. Tools.Warn = Tools._WarnEnabled;
  7718. }
  7719. else {
  7720. Tools.Warn = Tools._WarnDisabled;
  7721. }
  7722. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7723. Tools.Error = Tools._ErrorEnabled;
  7724. }
  7725. else {
  7726. Tools.Error = Tools._ErrorDisabled;
  7727. }
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Tools.IsWindowObjectExist = function () {
  7733. return (typeof window) !== "undefined";
  7734. };
  7735. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7736. get: function () {
  7737. return Tools._PerformanceNoneLogLevel;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7743. get: function () {
  7744. return Tools._PerformanceUserMarkLogLevel;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7750. get: function () {
  7751. return Tools._PerformanceConsoleLogLevel;
  7752. },
  7753. enumerable: true,
  7754. configurable: true
  7755. });
  7756. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7757. set: function (level) {
  7758. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7759. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7760. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7761. return;
  7762. }
  7763. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7764. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7765. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7766. return;
  7767. }
  7768. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7769. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7775. };
  7776. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7777. };
  7778. Tools._StartUserMark = function (counterName, condition) {
  7779. if (condition === void 0) { condition = true; }
  7780. if (!Tools._performance) {
  7781. if (!Tools.IsWindowObjectExist()) {
  7782. return;
  7783. }
  7784. Tools._performance = window.performance;
  7785. }
  7786. if (!condition || !Tools._performance.mark) {
  7787. return;
  7788. }
  7789. Tools._performance.mark(counterName + "-Begin");
  7790. };
  7791. Tools._EndUserMark = function (counterName, condition) {
  7792. if (condition === void 0) { condition = true; }
  7793. if (!condition || !Tools._performance.mark) {
  7794. return;
  7795. }
  7796. Tools._performance.mark(counterName + "-End");
  7797. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7798. };
  7799. Tools._StartPerformanceConsole = function (counterName, condition) {
  7800. if (condition === void 0) { condition = true; }
  7801. if (!condition) {
  7802. return;
  7803. }
  7804. Tools._StartUserMark(counterName, condition);
  7805. if (console.time) {
  7806. console.time(counterName);
  7807. }
  7808. };
  7809. Tools._EndPerformanceConsole = function (counterName, condition) {
  7810. if (condition === void 0) { condition = true; }
  7811. if (!condition) {
  7812. return;
  7813. }
  7814. Tools._EndUserMark(counterName, condition);
  7815. if (console.time) {
  7816. console.timeEnd(counterName);
  7817. }
  7818. };
  7819. Object.defineProperty(Tools, "Now", {
  7820. get: function () {
  7821. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7822. return window.performance.now();
  7823. }
  7824. return new Date().getTime();
  7825. },
  7826. enumerable: true,
  7827. configurable: true
  7828. });
  7829. /**
  7830. * This method will return the name of the class used to create the instance of the given object.
  7831. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7832. * @param object the object to get the class name from
  7833. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7834. */
  7835. Tools.GetClassName = function (object, isType) {
  7836. if (isType === void 0) { isType = false; }
  7837. var name = null;
  7838. if (!isType && object.getClassName) {
  7839. name = object.getClassName();
  7840. }
  7841. else {
  7842. if (object instanceof Object) {
  7843. var classObj = isType ? object : Object.getPrototypeOf(object);
  7844. name = classObj.constructor["__bjsclassName__"];
  7845. }
  7846. if (!name) {
  7847. name = typeof object;
  7848. }
  7849. }
  7850. return name;
  7851. };
  7852. Tools.First = function (array, predicate) {
  7853. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7854. var el = array_1[_i];
  7855. if (predicate(el)) {
  7856. return el;
  7857. }
  7858. }
  7859. return null;
  7860. };
  7861. /**
  7862. * This method will return the name of the full name of the class, including its owning module (if any).
  7863. * 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).
  7864. * @param object the object to get the class name from
  7865. * @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.
  7866. */
  7867. Tools.getFullClassName = function (object, isType) {
  7868. if (isType === void 0) { isType = false; }
  7869. var className = null;
  7870. var moduleName = null;
  7871. if (!isType && object.getClassName) {
  7872. className = object.getClassName();
  7873. }
  7874. else {
  7875. if (object instanceof Object) {
  7876. var classObj = isType ? object : Object.getPrototypeOf(object);
  7877. className = classObj.constructor["__bjsclassName__"];
  7878. moduleName = classObj.constructor["__bjsmoduleName__"];
  7879. }
  7880. if (!className) {
  7881. className = typeof object;
  7882. }
  7883. }
  7884. if (!className) {
  7885. return null;
  7886. }
  7887. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7888. };
  7889. /**
  7890. * 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.
  7891. * @param array
  7892. */
  7893. Tools.arrayOrStringFeeder = function (array) {
  7894. return function (index) {
  7895. if (index >= array.length) {
  7896. return null;
  7897. }
  7898. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7899. if (val && val.getHashCode) {
  7900. val = val.getHashCode();
  7901. }
  7902. if (typeof val === "string") {
  7903. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7904. }
  7905. return val;
  7906. };
  7907. };
  7908. /**
  7909. * Compute the hashCode of a stream of number
  7910. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7911. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7912. * @return the hash code computed
  7913. */
  7914. Tools.hashCodeFromStream = function (feeder) {
  7915. // Based from here: http://stackoverflow.com/a/7616484/802124
  7916. var hash = 0;
  7917. var index = 0;
  7918. var chr = feeder(index++);
  7919. while (chr != null) {
  7920. hash = ((hash << 5) - hash) + chr;
  7921. hash |= 0; // Convert to 32bit integer
  7922. chr = feeder(index++);
  7923. }
  7924. return hash;
  7925. };
  7926. Tools.BaseUrl = "";
  7927. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7928. /**
  7929. * Default behaviour for cors in the application.
  7930. * It can be a string if the expected behavior is identical in the entire app.
  7931. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7932. */
  7933. Tools.CorsBehavior = "anonymous";
  7934. Tools.UseFallbackTexture = true;
  7935. /**
  7936. * Use this object to register external classes like custom textures or material
  7937. * to allow the laoders to instantiate them
  7938. */
  7939. Tools.RegisteredExternalClasses = {};
  7940. // Used in case of a texture loading problem
  7941. 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";
  7942. Tools.PreprocessUrl = function (url) {
  7943. return url;
  7944. };
  7945. // Logs
  7946. Tools._NoneLogLevel = 0;
  7947. Tools._MessageLogLevel = 1;
  7948. Tools._WarningLogLevel = 2;
  7949. Tools._ErrorLogLevel = 4;
  7950. Tools._LogCache = "";
  7951. Tools.errorsCount = 0;
  7952. Tools.Log = Tools._LogEnabled;
  7953. Tools.Warn = Tools._WarnEnabled;
  7954. Tools.Error = Tools._ErrorEnabled;
  7955. // Performances
  7956. Tools._PerformanceNoneLogLevel = 0;
  7957. Tools._PerformanceUserMarkLogLevel = 1;
  7958. Tools._PerformanceConsoleLogLevel = 2;
  7959. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7960. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7961. return Tools;
  7962. }());
  7963. BABYLON.Tools = Tools;
  7964. /**
  7965. * This class is used to track a performance counter which is number based.
  7966. * The user has access to many properties which give statistics of different nature
  7967. *
  7968. * The implementer can track two kinds of Performance Counter: time and count
  7969. * 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.
  7970. * 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.
  7971. */
  7972. var PerfCounter = /** @class */ (function () {
  7973. function PerfCounter() {
  7974. this._startMonitoringTime = 0;
  7975. this._min = 0;
  7976. this._max = 0;
  7977. this._average = 0;
  7978. this._lastSecAverage = 0;
  7979. this._current = 0;
  7980. this._totalValueCount = 0;
  7981. this._totalAccumulated = 0;
  7982. this._lastSecAccumulated = 0;
  7983. this._lastSecTime = 0;
  7984. this._lastSecValueCount = 0;
  7985. }
  7986. Object.defineProperty(PerfCounter.prototype, "min", {
  7987. /**
  7988. * Returns the smallest value ever
  7989. */
  7990. get: function () {
  7991. return this._min;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. Object.defineProperty(PerfCounter.prototype, "max", {
  7997. /**
  7998. * Returns the biggest value ever
  7999. */
  8000. get: function () {
  8001. return this._max;
  8002. },
  8003. enumerable: true,
  8004. configurable: true
  8005. });
  8006. Object.defineProperty(PerfCounter.prototype, "average", {
  8007. /**
  8008. * Returns the average value since the performance counter is running
  8009. */
  8010. get: function () {
  8011. return this._average;
  8012. },
  8013. enumerable: true,
  8014. configurable: true
  8015. });
  8016. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8017. /**
  8018. * Returns the average value of the last second the counter was monitored
  8019. */
  8020. get: function () {
  8021. return this._lastSecAverage;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(PerfCounter.prototype, "current", {
  8027. /**
  8028. * Returns the current value
  8029. */
  8030. get: function () {
  8031. return this._current;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(PerfCounter.prototype, "total", {
  8037. get: function () {
  8038. return this._totalAccumulated;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(PerfCounter.prototype, "count", {
  8044. get: function () {
  8045. return this._totalValueCount;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. /**
  8051. * Call this method to start monitoring a new frame.
  8052. * 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.
  8053. */
  8054. PerfCounter.prototype.fetchNewFrame = function () {
  8055. this._totalValueCount++;
  8056. this._current = 0;
  8057. this._lastSecValueCount++;
  8058. };
  8059. /**
  8060. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8061. * @param newCount the count value to add to the monitored count
  8062. * @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.
  8063. */
  8064. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8065. if (!PerfCounter.Enabled) {
  8066. return;
  8067. }
  8068. this._current += newCount;
  8069. if (fetchResult) {
  8070. this._fetchResult();
  8071. }
  8072. };
  8073. /**
  8074. * Start monitoring this performance counter
  8075. */
  8076. PerfCounter.prototype.beginMonitoring = function () {
  8077. if (!PerfCounter.Enabled) {
  8078. return;
  8079. }
  8080. this._startMonitoringTime = Tools.Now;
  8081. };
  8082. /**
  8083. * Compute the time lapsed since the previous beginMonitoring() call.
  8084. * @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
  8085. */
  8086. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8087. if (newFrame === void 0) { newFrame = true; }
  8088. if (!PerfCounter.Enabled) {
  8089. return;
  8090. }
  8091. if (newFrame) {
  8092. this.fetchNewFrame();
  8093. }
  8094. var currentTime = Tools.Now;
  8095. this._current = currentTime - this._startMonitoringTime;
  8096. if (newFrame) {
  8097. this._fetchResult();
  8098. }
  8099. };
  8100. PerfCounter.prototype._fetchResult = function () {
  8101. this._totalAccumulated += this._current;
  8102. this._lastSecAccumulated += this._current;
  8103. // Min/Max update
  8104. this._min = Math.min(this._min, this._current);
  8105. this._max = Math.max(this._max, this._current);
  8106. this._average = this._totalAccumulated / this._totalValueCount;
  8107. // Reset last sec?
  8108. var now = Tools.Now;
  8109. if ((now - this._lastSecTime) > 1000) {
  8110. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8111. this._lastSecTime = now;
  8112. this._lastSecAccumulated = 0;
  8113. this._lastSecValueCount = 0;
  8114. }
  8115. };
  8116. PerfCounter.Enabled = true;
  8117. return PerfCounter;
  8118. }());
  8119. BABYLON.PerfCounter = PerfCounter;
  8120. /**
  8121. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8122. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8123. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8124. * @param name The name of the class, case should be preserved
  8125. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8126. */
  8127. function className(name, module) {
  8128. return function (target) {
  8129. target["__bjsclassName__"] = name;
  8130. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8131. };
  8132. }
  8133. BABYLON.className = className;
  8134. /**
  8135. * An implementation of a loop for asynchronous functions.
  8136. */
  8137. var AsyncLoop = /** @class */ (function () {
  8138. /**
  8139. * Constroctor.
  8140. * @param iterations the number of iterations.
  8141. * @param _fn the function to run each iteration
  8142. * @param _successCallback the callback that will be called upon succesful execution
  8143. * @param offset starting offset.
  8144. */
  8145. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8146. if (offset === void 0) { offset = 0; }
  8147. this.iterations = iterations;
  8148. this._fn = _fn;
  8149. this._successCallback = _successCallback;
  8150. this.index = offset - 1;
  8151. this._done = false;
  8152. }
  8153. /**
  8154. * Execute the next iteration. Must be called after the last iteration was finished.
  8155. */
  8156. AsyncLoop.prototype.executeNext = function () {
  8157. if (!this._done) {
  8158. if (this.index + 1 < this.iterations) {
  8159. ++this.index;
  8160. this._fn(this);
  8161. }
  8162. else {
  8163. this.breakLoop();
  8164. }
  8165. }
  8166. };
  8167. /**
  8168. * Break the loop and run the success callback.
  8169. */
  8170. AsyncLoop.prototype.breakLoop = function () {
  8171. this._done = true;
  8172. this._successCallback();
  8173. };
  8174. /**
  8175. * Helper function
  8176. */
  8177. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8178. if (offset === void 0) { offset = 0; }
  8179. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8180. loop.executeNext();
  8181. return loop;
  8182. };
  8183. /**
  8184. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8185. * @param iterations total number of iterations
  8186. * @param syncedIterations number of synchronous iterations in each async iteration.
  8187. * @param fn the function to call each iteration.
  8188. * @param callback a success call back that will be called when iterating stops.
  8189. * @param breakFunction a break condition (optional)
  8190. * @param timeout timeout settings for the setTimeout function. default - 0.
  8191. * @constructor
  8192. */
  8193. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8194. if (timeout === void 0) { timeout = 0; }
  8195. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8196. if (breakFunction && breakFunction())
  8197. loop.breakLoop();
  8198. else {
  8199. setTimeout(function () {
  8200. for (var i = 0; i < syncedIterations; ++i) {
  8201. var iteration = (loop.index * syncedIterations) + i;
  8202. if (iteration >= iterations)
  8203. break;
  8204. fn(iteration);
  8205. if (breakFunction && breakFunction()) {
  8206. loop.breakLoop();
  8207. break;
  8208. }
  8209. }
  8210. loop.executeNext();
  8211. }, timeout);
  8212. }
  8213. }, callback);
  8214. };
  8215. return AsyncLoop;
  8216. }());
  8217. BABYLON.AsyncLoop = AsyncLoop;
  8218. })(BABYLON || (BABYLON = {}));
  8219. //# sourceMappingURL=babylon.tools.js.map
  8220. var BABYLON;
  8221. (function (BABYLON) {
  8222. var _AlphaState = /** @class */ (function () {
  8223. /**
  8224. * Initializes the state.
  8225. */
  8226. function _AlphaState() {
  8227. this._isAlphaBlendDirty = false;
  8228. this._isBlendFunctionParametersDirty = false;
  8229. this._isBlendEquationParametersDirty = false;
  8230. this._isBlendConstantsDirty = false;
  8231. this._alphaBlend = false;
  8232. this._blendFunctionParameters = new Array(4);
  8233. this._blendEquationParameters = new Array(2);
  8234. this._blendConstants = new Array(4);
  8235. this.reset();
  8236. }
  8237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8238. get: function () {
  8239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8245. get: function () {
  8246. return this._alphaBlend;
  8247. },
  8248. set: function (value) {
  8249. if (this._alphaBlend === value) {
  8250. return;
  8251. }
  8252. this._alphaBlend = value;
  8253. this._isAlphaBlendDirty = true;
  8254. },
  8255. enumerable: true,
  8256. configurable: true
  8257. });
  8258. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8259. if (this._blendConstants[0] === r &&
  8260. this._blendConstants[1] === g &&
  8261. this._blendConstants[2] === b &&
  8262. this._blendConstants[3] === a) {
  8263. return;
  8264. }
  8265. this._blendConstants[0] = r;
  8266. this._blendConstants[1] = g;
  8267. this._blendConstants[2] = b;
  8268. this._blendConstants[3] = a;
  8269. this._isBlendConstantsDirty = true;
  8270. };
  8271. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8272. if (this._blendFunctionParameters[0] === value0 &&
  8273. this._blendFunctionParameters[1] === value1 &&
  8274. this._blendFunctionParameters[2] === value2 &&
  8275. this._blendFunctionParameters[3] === value3) {
  8276. return;
  8277. }
  8278. this._blendFunctionParameters[0] = value0;
  8279. this._blendFunctionParameters[1] = value1;
  8280. this._blendFunctionParameters[2] = value2;
  8281. this._blendFunctionParameters[3] = value3;
  8282. this._isBlendFunctionParametersDirty = true;
  8283. };
  8284. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8285. if (this._blendEquationParameters[0] === rgb &&
  8286. this._blendEquationParameters[1] === alpha) {
  8287. return;
  8288. }
  8289. this._blendEquationParameters[0] = rgb;
  8290. this._blendEquationParameters[1] = alpha;
  8291. this._isBlendEquationParametersDirty = true;
  8292. };
  8293. _AlphaState.prototype.reset = function () {
  8294. this._alphaBlend = false;
  8295. this._blendFunctionParameters[0] = null;
  8296. this._blendFunctionParameters[1] = null;
  8297. this._blendFunctionParameters[2] = null;
  8298. this._blendFunctionParameters[3] = null;
  8299. this._blendEquationParameters[0] = null;
  8300. this._blendEquationParameters[1] = null;
  8301. this._blendConstants[0] = null;
  8302. this._blendConstants[1] = null;
  8303. this._blendConstants[2] = null;
  8304. this._blendConstants[3] = null;
  8305. this._isAlphaBlendDirty = true;
  8306. this._isBlendFunctionParametersDirty = false;
  8307. this._isBlendEquationParametersDirty = false;
  8308. this._isBlendConstantsDirty = false;
  8309. };
  8310. _AlphaState.prototype.apply = function (gl) {
  8311. if (!this.isDirty) {
  8312. return;
  8313. }
  8314. // Alpha blend
  8315. if (this._isAlphaBlendDirty) {
  8316. if (this._alphaBlend) {
  8317. gl.enable(gl.BLEND);
  8318. }
  8319. else {
  8320. gl.disable(gl.BLEND);
  8321. }
  8322. this._isAlphaBlendDirty = false;
  8323. }
  8324. // Alpha function
  8325. if (this._isBlendFunctionParametersDirty) {
  8326. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8327. this._isBlendFunctionParametersDirty = false;
  8328. }
  8329. // Alpha equation
  8330. if (this._isBlendEquationParametersDirty) {
  8331. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8332. this._isBlendEquationParametersDirty = false;
  8333. }
  8334. // Constants
  8335. if (this._isBlendConstantsDirty) {
  8336. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8337. this._isBlendConstantsDirty = false;
  8338. }
  8339. };
  8340. return _AlphaState;
  8341. }());
  8342. BABYLON._AlphaState = _AlphaState;
  8343. })(BABYLON || (BABYLON = {}));
  8344. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8345. var BABYLON;
  8346. (function (BABYLON) {
  8347. var _DepthCullingState = /** @class */ (function () {
  8348. /**
  8349. * Initializes the state.
  8350. */
  8351. function _DepthCullingState() {
  8352. this._isDepthTestDirty = false;
  8353. this._isDepthMaskDirty = false;
  8354. this._isDepthFuncDirty = false;
  8355. this._isCullFaceDirty = false;
  8356. this._isCullDirty = false;
  8357. this._isZOffsetDirty = false;
  8358. this._isFrontFaceDirty = false;
  8359. this.reset();
  8360. }
  8361. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8362. get: function () {
  8363. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8369. get: function () {
  8370. return this._zOffset;
  8371. },
  8372. set: function (value) {
  8373. if (this._zOffset === value) {
  8374. return;
  8375. }
  8376. this._zOffset = value;
  8377. this._isZOffsetDirty = true;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8383. get: function () {
  8384. return this._cullFace;
  8385. },
  8386. set: function (value) {
  8387. if (this._cullFace === value) {
  8388. return;
  8389. }
  8390. this._cullFace = value;
  8391. this._isCullFaceDirty = true;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8397. get: function () {
  8398. return this._cull;
  8399. },
  8400. set: function (value) {
  8401. if (this._cull === value) {
  8402. return;
  8403. }
  8404. this._cull = value;
  8405. this._isCullDirty = true;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8411. get: function () {
  8412. return this._depthFunc;
  8413. },
  8414. set: function (value) {
  8415. if (this._depthFunc === value) {
  8416. return;
  8417. }
  8418. this._depthFunc = value;
  8419. this._isDepthFuncDirty = true;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8425. get: function () {
  8426. return this._depthMask;
  8427. },
  8428. set: function (value) {
  8429. if (this._depthMask === value) {
  8430. return;
  8431. }
  8432. this._depthMask = value;
  8433. this._isDepthMaskDirty = true;
  8434. },
  8435. enumerable: true,
  8436. configurable: true
  8437. });
  8438. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8439. get: function () {
  8440. return this._depthTest;
  8441. },
  8442. set: function (value) {
  8443. if (this._depthTest === value) {
  8444. return;
  8445. }
  8446. this._depthTest = value;
  8447. this._isDepthTestDirty = true;
  8448. },
  8449. enumerable: true,
  8450. configurable: true
  8451. });
  8452. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8453. get: function () {
  8454. return this._frontFace;
  8455. },
  8456. set: function (value) {
  8457. if (this._frontFace === value) {
  8458. return;
  8459. }
  8460. this._frontFace = value;
  8461. this._isFrontFaceDirty = true;
  8462. },
  8463. enumerable: true,
  8464. configurable: true
  8465. });
  8466. _DepthCullingState.prototype.reset = function () {
  8467. this._depthMask = true;
  8468. this._depthTest = true;
  8469. this._depthFunc = null;
  8470. this._cullFace = null;
  8471. this._cull = null;
  8472. this._zOffset = 0;
  8473. this._frontFace = null;
  8474. this._isDepthTestDirty = true;
  8475. this._isDepthMaskDirty = true;
  8476. this._isDepthFuncDirty = false;
  8477. this._isCullFaceDirty = false;
  8478. this._isCullDirty = false;
  8479. this._isZOffsetDirty = false;
  8480. this._isFrontFaceDirty = false;
  8481. };
  8482. _DepthCullingState.prototype.apply = function (gl) {
  8483. if (!this.isDirty) {
  8484. return;
  8485. }
  8486. // Cull
  8487. if (this._isCullDirty) {
  8488. if (this.cull) {
  8489. gl.enable(gl.CULL_FACE);
  8490. }
  8491. else {
  8492. gl.disable(gl.CULL_FACE);
  8493. }
  8494. this._isCullDirty = false;
  8495. }
  8496. // Cull face
  8497. if (this._isCullFaceDirty) {
  8498. gl.cullFace(this.cullFace);
  8499. this._isCullFaceDirty = false;
  8500. }
  8501. // Depth mask
  8502. if (this._isDepthMaskDirty) {
  8503. gl.depthMask(this.depthMask);
  8504. this._isDepthMaskDirty = false;
  8505. }
  8506. // Depth test
  8507. if (this._isDepthTestDirty) {
  8508. if (this.depthTest) {
  8509. gl.enable(gl.DEPTH_TEST);
  8510. }
  8511. else {
  8512. gl.disable(gl.DEPTH_TEST);
  8513. }
  8514. this._isDepthTestDirty = false;
  8515. }
  8516. // Depth func
  8517. if (this._isDepthFuncDirty) {
  8518. gl.depthFunc(this.depthFunc);
  8519. this._isDepthFuncDirty = false;
  8520. }
  8521. // zOffset
  8522. if (this._isZOffsetDirty) {
  8523. if (this.zOffset) {
  8524. gl.enable(gl.POLYGON_OFFSET_FILL);
  8525. gl.polygonOffset(this.zOffset, 0);
  8526. }
  8527. else {
  8528. gl.disable(gl.POLYGON_OFFSET_FILL);
  8529. }
  8530. this._isZOffsetDirty = false;
  8531. }
  8532. // Front face
  8533. if (this._isFrontFaceDirty) {
  8534. gl.frontFace(this.frontFace);
  8535. this._isFrontFaceDirty = false;
  8536. }
  8537. };
  8538. return _DepthCullingState;
  8539. }());
  8540. BABYLON._DepthCullingState = _DepthCullingState;
  8541. })(BABYLON || (BABYLON = {}));
  8542. //# sourceMappingURL=babylon.depthCullingState.js.map
  8543. var BABYLON;
  8544. (function (BABYLON) {
  8545. var _StencilState = /** @class */ (function () {
  8546. function _StencilState() {
  8547. this._isStencilTestDirty = false;
  8548. this._isStencilMaskDirty = false;
  8549. this._isStencilFuncDirty = false;
  8550. this._isStencilOpDirty = false;
  8551. this.reset();
  8552. }
  8553. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8554. get: function () {
  8555. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8561. get: function () {
  8562. return this._stencilFunc;
  8563. },
  8564. set: function (value) {
  8565. if (this._stencilFunc === value) {
  8566. return;
  8567. }
  8568. this._stencilFunc = value;
  8569. this._isStencilFuncDirty = true;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8575. get: function () {
  8576. return this._stencilFuncRef;
  8577. },
  8578. set: function (value) {
  8579. if (this._stencilFuncRef === value) {
  8580. return;
  8581. }
  8582. this._stencilFuncRef = value;
  8583. this._isStencilFuncDirty = true;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8589. get: function () {
  8590. return this._stencilFuncMask;
  8591. },
  8592. set: function (value) {
  8593. if (this._stencilFuncMask === value) {
  8594. return;
  8595. }
  8596. this._stencilFuncMask = value;
  8597. this._isStencilFuncDirty = true;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8603. get: function () {
  8604. return this._stencilOpStencilFail;
  8605. },
  8606. set: function (value) {
  8607. if (this._stencilOpStencilFail === value) {
  8608. return;
  8609. }
  8610. this._stencilOpStencilFail = value;
  8611. this._isStencilOpDirty = true;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8617. get: function () {
  8618. return this._stencilOpDepthFail;
  8619. },
  8620. set: function (value) {
  8621. if (this._stencilOpDepthFail === value) {
  8622. return;
  8623. }
  8624. this._stencilOpDepthFail = value;
  8625. this._isStencilOpDirty = true;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8631. get: function () {
  8632. return this._stencilOpStencilDepthPass;
  8633. },
  8634. set: function (value) {
  8635. if (this._stencilOpStencilDepthPass === value) {
  8636. return;
  8637. }
  8638. this._stencilOpStencilDepthPass = value;
  8639. this._isStencilOpDirty = true;
  8640. },
  8641. enumerable: true,
  8642. configurable: true
  8643. });
  8644. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8645. get: function () {
  8646. return this._stencilMask;
  8647. },
  8648. set: function (value) {
  8649. if (this._stencilMask === value) {
  8650. return;
  8651. }
  8652. this._stencilMask = value;
  8653. this._isStencilMaskDirty = true;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8659. get: function () {
  8660. return this._stencilTest;
  8661. },
  8662. set: function (value) {
  8663. if (this._stencilTest === value) {
  8664. return;
  8665. }
  8666. this._stencilTest = value;
  8667. this._isStencilTestDirty = true;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. _StencilState.prototype.reset = function () {
  8673. this._stencilTest = false;
  8674. this._stencilMask = 0xFF;
  8675. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8676. this._stencilFuncRef = 1;
  8677. this._stencilFuncMask = 0xFF;
  8678. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8679. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8680. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8681. this._isStencilTestDirty = true;
  8682. this._isStencilMaskDirty = true;
  8683. this._isStencilFuncDirty = true;
  8684. this._isStencilOpDirty = true;
  8685. };
  8686. _StencilState.prototype.apply = function (gl) {
  8687. if (!this.isDirty) {
  8688. return;
  8689. }
  8690. // Stencil test
  8691. if (this._isStencilTestDirty) {
  8692. if (this.stencilTest) {
  8693. gl.enable(gl.STENCIL_TEST);
  8694. }
  8695. else {
  8696. gl.disable(gl.STENCIL_TEST);
  8697. }
  8698. this._isStencilTestDirty = false;
  8699. }
  8700. // Stencil mask
  8701. if (this._isStencilMaskDirty) {
  8702. gl.stencilMask(this.stencilMask);
  8703. this._isStencilMaskDirty = false;
  8704. }
  8705. // Stencil func
  8706. if (this._isStencilFuncDirty) {
  8707. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8708. this._isStencilFuncDirty = false;
  8709. }
  8710. // Stencil op
  8711. if (this._isStencilOpDirty) {
  8712. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8713. this._isStencilOpDirty = false;
  8714. }
  8715. };
  8716. return _StencilState;
  8717. }());
  8718. BABYLON._StencilState = _StencilState;
  8719. })(BABYLON || (BABYLON = {}));
  8720. //# sourceMappingURL=babylon.stencilState.js.map
  8721. var BABYLON;
  8722. (function (BABYLON) {
  8723. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8724. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8725. };
  8726. var compileRawShader = function (gl, source, type) {
  8727. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8728. gl.shaderSource(shader, source);
  8729. gl.compileShader(shader);
  8730. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8731. var log = gl.getShaderInfoLog(shader);
  8732. if (log) {
  8733. throw new Error(log);
  8734. }
  8735. }
  8736. if (!shader) {
  8737. throw new Error("Something went wrong while compile the shader.");
  8738. }
  8739. return shader;
  8740. };
  8741. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8742. var magFilter = gl.NEAREST;
  8743. var minFilter = gl.NEAREST;
  8744. switch (samplingMode) {
  8745. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8746. magFilter = gl.LINEAR;
  8747. if (generateMipMaps) {
  8748. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8749. }
  8750. else {
  8751. minFilter = gl.LINEAR;
  8752. }
  8753. break;
  8754. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8755. magFilter = gl.LINEAR;
  8756. if (generateMipMaps) {
  8757. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8758. }
  8759. else {
  8760. minFilter = gl.LINEAR;
  8761. }
  8762. break;
  8763. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8764. magFilter = gl.NEAREST;
  8765. if (generateMipMaps) {
  8766. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8767. }
  8768. else {
  8769. minFilter = gl.NEAREST;
  8770. }
  8771. break;
  8772. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8773. magFilter = gl.NEAREST;
  8774. if (generateMipMaps) {
  8775. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8776. }
  8777. else {
  8778. minFilter = gl.NEAREST;
  8779. }
  8780. break;
  8781. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8782. magFilter = gl.NEAREST;
  8783. if (generateMipMaps) {
  8784. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8785. }
  8786. else {
  8787. minFilter = gl.LINEAR;
  8788. }
  8789. break;
  8790. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8791. magFilter = gl.NEAREST;
  8792. if (generateMipMaps) {
  8793. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8794. }
  8795. else {
  8796. minFilter = gl.LINEAR;
  8797. }
  8798. break;
  8799. case BABYLON.Texture.NEAREST_LINEAR:
  8800. magFilter = gl.NEAREST;
  8801. minFilter = gl.LINEAR;
  8802. break;
  8803. case BABYLON.Texture.NEAREST_NEAREST:
  8804. magFilter = gl.NEAREST;
  8805. minFilter = gl.NEAREST;
  8806. break;
  8807. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8808. magFilter = gl.LINEAR;
  8809. if (generateMipMaps) {
  8810. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8811. }
  8812. else {
  8813. minFilter = gl.NEAREST;
  8814. }
  8815. break;
  8816. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8817. magFilter = gl.LINEAR;
  8818. if (generateMipMaps) {
  8819. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8820. }
  8821. else {
  8822. minFilter = gl.NEAREST;
  8823. }
  8824. break;
  8825. case BABYLON.Texture.LINEAR_LINEAR:
  8826. magFilter = gl.LINEAR;
  8827. minFilter = gl.LINEAR;
  8828. break;
  8829. case BABYLON.Texture.LINEAR_NEAREST:
  8830. magFilter = gl.LINEAR;
  8831. minFilter = gl.NEAREST;
  8832. break;
  8833. }
  8834. return {
  8835. min: minFilter,
  8836. mag: magFilter
  8837. };
  8838. };
  8839. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8840. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8841. var img;
  8842. var onload = function () {
  8843. loadedImages[index] = img;
  8844. loadedImages._internalCount++;
  8845. if (scene) {
  8846. scene._removePendingData(img);
  8847. }
  8848. if (loadedImages._internalCount === 6) {
  8849. onfinish(loadedImages);
  8850. }
  8851. };
  8852. var onerror = function (message, exception) {
  8853. if (scene) {
  8854. scene._removePendingData(img);
  8855. }
  8856. if (onErrorCallBack) {
  8857. onErrorCallBack(message, exception);
  8858. }
  8859. };
  8860. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8861. if (scene) {
  8862. scene._addPendingData(img);
  8863. }
  8864. };
  8865. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8866. if (onError === void 0) { onError = null; }
  8867. var loadedImages = [];
  8868. loadedImages._internalCount = 0;
  8869. for (var index = 0; index < 6; index++) {
  8870. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8871. }
  8872. };
  8873. var BufferPointer = /** @class */ (function () {
  8874. function BufferPointer() {
  8875. }
  8876. return BufferPointer;
  8877. }());
  8878. var InstancingAttributeInfo = /** @class */ (function () {
  8879. function InstancingAttributeInfo() {
  8880. }
  8881. return InstancingAttributeInfo;
  8882. }());
  8883. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8884. /**
  8885. * Define options used to create a render target texture
  8886. */
  8887. var RenderTargetCreationOptions = /** @class */ (function () {
  8888. function RenderTargetCreationOptions() {
  8889. }
  8890. return RenderTargetCreationOptions;
  8891. }());
  8892. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8893. /**
  8894. * Regroup several parameters relative to the browser in use
  8895. */
  8896. var EngineCapabilities = /** @class */ (function () {
  8897. function EngineCapabilities() {
  8898. }
  8899. return EngineCapabilities;
  8900. }());
  8901. BABYLON.EngineCapabilities = EngineCapabilities;
  8902. /**
  8903. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8904. */
  8905. var Engine = /** @class */ (function () {
  8906. /**
  8907. * @constructor
  8908. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8909. * @param antialias defines enable antialiasing (default: false)
  8910. * @param options defines further options to be sent to the getContext() function
  8911. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8912. */
  8913. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8914. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8915. var _this = this;
  8916. // Public members
  8917. this.forcePOTTextures = false;
  8918. this.isFullscreen = false;
  8919. this.isPointerLock = false;
  8920. this.cullBackFaces = true;
  8921. this.renderEvenInBackground = true;
  8922. this.preventCacheWipeBetweenFrames = false;
  8923. // To enable/disable IDB support and avoid XHR on .manifest
  8924. this.enableOfflineSupport = false;
  8925. this.scenes = new Array();
  8926. this.postProcesses = new Array();
  8927. // Observables
  8928. /**
  8929. * Observable event triggered each time the rendering canvas is resized
  8930. */
  8931. this.onResizeObservable = new BABYLON.Observable();
  8932. /**
  8933. * Observable event triggered each time the canvas loses focus
  8934. */
  8935. this.onCanvasBlurObservable = new BABYLON.Observable();
  8936. /**
  8937. * Observable event triggered each time the canvas gains focus
  8938. */
  8939. this.onCanvasFocusObservable = new BABYLON.Observable();
  8940. /**
  8941. * Observable event triggered each time the canvas receives pointerout event
  8942. */
  8943. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8944. /**
  8945. * Observable event triggered before each texture is initialized
  8946. */
  8947. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8948. //WebVR
  8949. this._vrDisplay = undefined;
  8950. this._vrSupported = false;
  8951. this._vrExclusivePointerMode = false;
  8952. // Uniform buffers list
  8953. this.disableUniformBuffers = false;
  8954. this._uniformBuffers = new Array();
  8955. // Observables
  8956. /**
  8957. * Observable raised when the engine begins a new frame
  8958. */
  8959. this.onBeginFrameObservable = new BABYLON.Observable();
  8960. /**
  8961. * Observable raised when the engine ends the current frame
  8962. */
  8963. this.onEndFrameObservable = new BABYLON.Observable();
  8964. /**
  8965. * Observable raised when the engine is about to compile a shader
  8966. */
  8967. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8968. /**
  8969. * Observable raised when the engine has jsut compiled a shader
  8970. */
  8971. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8972. this._windowIsBackground = false;
  8973. this._webGLVersion = 1.0;
  8974. this._badOS = false;
  8975. this._badDesktopOS = false;
  8976. /**
  8977. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8978. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8979. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8980. */
  8981. this.disableTextureBindingOptimization = false;
  8982. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8983. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8984. this.onVRRequestPresentStart = new BABYLON.Observable();
  8985. this._colorWrite = true;
  8986. this._drawCalls = new BABYLON.PerfCounter();
  8987. this._textureCollisions = new BABYLON.PerfCounter();
  8988. this._renderingQueueLaunched = false;
  8989. this._activeRenderLoops = new Array();
  8990. // Deterministic lockstepMaxSteps
  8991. this._deterministicLockstep = false;
  8992. this._lockstepMaxSteps = 4;
  8993. // Lost context
  8994. this.onContextLostObservable = new BABYLON.Observable();
  8995. this.onContextRestoredObservable = new BABYLON.Observable();
  8996. this._contextWasLost = false;
  8997. this._doNotHandleContextLost = false;
  8998. // FPS
  8999. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9000. this._fps = 60;
  9001. this._deltaTime = 0;
  9002. /**
  9003. * Turn this value on if you want to pause FPS computation when in background
  9004. */
  9005. this.disablePerformanceMonitorInBackground = false;
  9006. // States
  9007. this._depthCullingState = new BABYLON._DepthCullingState();
  9008. this._stencilState = new BABYLON._StencilState();
  9009. this._alphaState = new BABYLON._AlphaState();
  9010. this._alphaMode = Engine.ALPHA_DISABLE;
  9011. // Cache
  9012. this._internalTexturesCache = new Array();
  9013. this._activeChannel = 0;
  9014. this._currentTextureChannel = -1;
  9015. this._boundTexturesCache = {};
  9016. this._compiledEffects = {};
  9017. this._vertexAttribArraysEnabled = [];
  9018. this._uintIndicesCurrentlySet = false;
  9019. this._currentBoundBuffer = new Array();
  9020. this._currentBufferPointers = new Array();
  9021. this._currentInstanceLocations = new Array();
  9022. this._currentInstanceBuffers = new Array();
  9023. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9024. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9025. this._vaoRecordInProgress = false;
  9026. this._mustWipeVertexAttributes = false;
  9027. this._nextFreeTextureSlots = new Array();
  9028. this._maxSimultaneousTextures = 0;
  9029. this._activeRequests = new Array();
  9030. // Hardware supported Compressed Textures
  9031. this._texturesSupported = new Array();
  9032. this._onVRFullScreenTriggered = function () {
  9033. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9034. //get the old size before we change
  9035. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9036. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9037. //get the width and height, change the render size
  9038. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9039. _this.setHardwareScalingLevel(1);
  9040. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9041. }
  9042. else {
  9043. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9044. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9045. }
  9046. };
  9047. this._boundUniforms = {};
  9048. var canvas = null;
  9049. Engine.Instances.push(this);
  9050. if (!canvasOrContext) {
  9051. return;
  9052. }
  9053. options = options || {};
  9054. if (canvasOrContext.getContext) {
  9055. canvas = canvasOrContext;
  9056. this._renderingCanvas = canvas;
  9057. if (antialias != null) {
  9058. options.antialias = antialias;
  9059. }
  9060. if (options.deterministicLockstep === undefined) {
  9061. options.deterministicLockstep = false;
  9062. }
  9063. if (options.lockstepMaxSteps === undefined) {
  9064. options.lockstepMaxSteps = 4;
  9065. }
  9066. if (options.preserveDrawingBuffer === undefined) {
  9067. options.preserveDrawingBuffer = false;
  9068. }
  9069. if (options.audioEngine === undefined) {
  9070. options.audioEngine = true;
  9071. }
  9072. if (options.stencil === undefined) {
  9073. options.stencil = true;
  9074. }
  9075. this._deterministicLockstep = options.deterministicLockstep;
  9076. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9077. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9078. // Exceptions
  9079. if (navigator && navigator.userAgent) {
  9080. var ua = navigator.userAgent;
  9081. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9082. var exception = _a[_i];
  9083. var key = exception.key;
  9084. var targets = exception.targets;
  9085. if (ua.indexOf(key) > -1) {
  9086. if (exception.capture && exception.captureConstraint) {
  9087. var capture = exception.capture;
  9088. var constraint = exception.captureConstraint;
  9089. var regex = new RegExp(capture);
  9090. var matches = regex.exec(ua);
  9091. if (matches && matches.length > 0) {
  9092. var capturedValue = parseInt(matches[matches.length - 1]);
  9093. if (capturedValue >= constraint) {
  9094. continue;
  9095. }
  9096. }
  9097. }
  9098. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9099. var target = targets_1[_b];
  9100. switch (target) {
  9101. case "uniformBuffer":
  9102. this.disableUniformBuffers = true;
  9103. break;
  9104. case "textureBindingOptimization":
  9105. this.disableTextureBindingOptimization = true;
  9106. break;
  9107. }
  9108. }
  9109. break;
  9110. }
  9111. }
  9112. }
  9113. // GL
  9114. if (!options.disableWebGL2Support) {
  9115. try {
  9116. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9117. if (this._gl) {
  9118. this._webGLVersion = 2.0;
  9119. }
  9120. }
  9121. catch (e) {
  9122. // Do nothing
  9123. }
  9124. }
  9125. if (!this._gl) {
  9126. if (!canvas) {
  9127. throw new Error("The provided canvas is null or undefined.");
  9128. }
  9129. try {
  9130. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9131. }
  9132. catch (e) {
  9133. throw new Error("WebGL not supported");
  9134. }
  9135. }
  9136. if (!this._gl) {
  9137. throw new Error("WebGL not supported");
  9138. }
  9139. this._onCanvasFocus = function () {
  9140. _this.onCanvasFocusObservable.notifyObservers(_this);
  9141. };
  9142. this._onCanvasBlur = function () {
  9143. _this.onCanvasBlurObservable.notifyObservers(_this);
  9144. };
  9145. canvas.addEventListener("focus", this._onCanvasFocus);
  9146. canvas.addEventListener("blur", this._onCanvasBlur);
  9147. this._onBlur = function () {
  9148. if (_this.disablePerformanceMonitorInBackground) {
  9149. _this._performanceMonitor.disable();
  9150. }
  9151. _this._windowIsBackground = true;
  9152. };
  9153. this._onFocus = function () {
  9154. if (_this.disablePerformanceMonitorInBackground) {
  9155. _this._performanceMonitor.enable();
  9156. }
  9157. _this._windowIsBackground = false;
  9158. };
  9159. this._onCanvasPointerOut = function () {
  9160. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9161. };
  9162. window.addEventListener("blur", this._onBlur);
  9163. window.addEventListener("focus", this._onFocus);
  9164. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9165. // Context lost
  9166. if (!this._doNotHandleContextLost) {
  9167. this._onContextLost = function (evt) {
  9168. evt.preventDefault();
  9169. _this._contextWasLost = true;
  9170. BABYLON.Tools.Warn("WebGL context lost.");
  9171. _this.onContextLostObservable.notifyObservers(_this);
  9172. };
  9173. this._onContextRestored = function (evt) {
  9174. // Adding a timeout to avoid race condition at browser level
  9175. setTimeout(function () {
  9176. // Rebuild gl context
  9177. _this._initGLContext();
  9178. // Rebuild effects
  9179. _this._rebuildEffects();
  9180. // Rebuild textures
  9181. _this._rebuildInternalTextures();
  9182. // Rebuild buffers
  9183. _this._rebuildBuffers();
  9184. // Cache
  9185. _this.wipeCaches(true);
  9186. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9187. _this.onContextRestoredObservable.notifyObservers(_this);
  9188. _this._contextWasLost = false;
  9189. }, 0);
  9190. };
  9191. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9192. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9193. }
  9194. }
  9195. else {
  9196. this._gl = canvasOrContext;
  9197. this._renderingCanvas = this._gl.canvas;
  9198. if (this._gl.renderbufferStorageMultisample) {
  9199. this._webGLVersion = 2.0;
  9200. }
  9201. options.stencil = this._gl.getContextAttributes().stencil;
  9202. }
  9203. // Viewport
  9204. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9205. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9206. this.resize();
  9207. this._isStencilEnable = options.stencil ? true : false;
  9208. this._initGLContext();
  9209. if (canvas) {
  9210. // Fullscreen
  9211. this._onFullscreenChange = function () {
  9212. if (document.fullscreen !== undefined) {
  9213. _this.isFullscreen = document.fullscreen;
  9214. }
  9215. else if (document.mozFullScreen !== undefined) {
  9216. _this.isFullscreen = document.mozFullScreen;
  9217. }
  9218. else if (document.webkitIsFullScreen !== undefined) {
  9219. _this.isFullscreen = document.webkitIsFullScreen;
  9220. }
  9221. else if (document.msIsFullScreen !== undefined) {
  9222. _this.isFullscreen = document.msIsFullScreen;
  9223. }
  9224. // Pointer lock
  9225. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9226. canvas.requestPointerLock = canvas.requestPointerLock ||
  9227. canvas.msRequestPointerLock ||
  9228. canvas.mozRequestPointerLock ||
  9229. canvas.webkitRequestPointerLock;
  9230. if (canvas.requestPointerLock) {
  9231. canvas.requestPointerLock();
  9232. }
  9233. }
  9234. };
  9235. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9236. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9237. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9238. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9239. // Pointer lock
  9240. this._onPointerLockChange = function () {
  9241. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9242. document.webkitPointerLockElement === canvas ||
  9243. document.msPointerLockElement === canvas ||
  9244. document.pointerLockElement === canvas);
  9245. };
  9246. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9247. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9248. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9249. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9250. this._onVRDisplayPointerRestricted = function () {
  9251. if (canvas) {
  9252. canvas.requestPointerLock();
  9253. }
  9254. };
  9255. this._onVRDisplayPointerUnrestricted = function () {
  9256. document.exitPointerLock();
  9257. };
  9258. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9259. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9260. }
  9261. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9262. Engine.audioEngine = new BABYLON.AudioEngine();
  9263. }
  9264. // Prepare buffer pointers
  9265. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9266. this._currentBufferPointers[i] = new BufferPointer();
  9267. }
  9268. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9269. // Load WebVR Devices
  9270. if (options.autoEnableWebVR) {
  9271. this.initWebVR();
  9272. }
  9273. // Detect if we are running on a faulty buggy OS.
  9274. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9275. // Detect if we are running on a faulty buggy desktop OS.
  9276. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9277. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9278. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9279. }
  9280. Object.defineProperty(Engine, "LastCreatedEngine", {
  9281. get: function () {
  9282. if (Engine.Instances.length === 0) {
  9283. return null;
  9284. }
  9285. return Engine.Instances[Engine.Instances.length - 1];
  9286. },
  9287. enumerable: true,
  9288. configurable: true
  9289. });
  9290. Object.defineProperty(Engine, "LastCreatedScene", {
  9291. get: function () {
  9292. var lastCreatedEngine = Engine.LastCreatedEngine;
  9293. if (!lastCreatedEngine) {
  9294. return null;
  9295. }
  9296. if (lastCreatedEngine.scenes.length === 0) {
  9297. return null;
  9298. }
  9299. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. /**
  9305. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9306. */
  9307. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9308. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9309. var engine = Engine.Instances[engineIndex];
  9310. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9311. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9312. }
  9313. }
  9314. };
  9315. Object.defineProperty(Engine, "NEVER", {
  9316. get: function () {
  9317. return Engine._NEVER;
  9318. },
  9319. enumerable: true,
  9320. configurable: true
  9321. });
  9322. Object.defineProperty(Engine, "ALWAYS", {
  9323. get: function () {
  9324. return Engine._ALWAYS;
  9325. },
  9326. enumerable: true,
  9327. configurable: true
  9328. });
  9329. Object.defineProperty(Engine, "LESS", {
  9330. get: function () {
  9331. return Engine._LESS;
  9332. },
  9333. enumerable: true,
  9334. configurable: true
  9335. });
  9336. Object.defineProperty(Engine, "EQUAL", {
  9337. get: function () {
  9338. return Engine._EQUAL;
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Object.defineProperty(Engine, "LEQUAL", {
  9344. get: function () {
  9345. return Engine._LEQUAL;
  9346. },
  9347. enumerable: true,
  9348. configurable: true
  9349. });
  9350. Object.defineProperty(Engine, "GREATER", {
  9351. get: function () {
  9352. return Engine._GREATER;
  9353. },
  9354. enumerable: true,
  9355. configurable: true
  9356. });
  9357. Object.defineProperty(Engine, "GEQUAL", {
  9358. get: function () {
  9359. return Engine._GEQUAL;
  9360. },
  9361. enumerable: true,
  9362. configurable: true
  9363. });
  9364. Object.defineProperty(Engine, "NOTEQUAL", {
  9365. get: function () {
  9366. return Engine._NOTEQUAL;
  9367. },
  9368. enumerable: true,
  9369. configurable: true
  9370. });
  9371. Object.defineProperty(Engine, "KEEP", {
  9372. get: function () {
  9373. return Engine._KEEP;
  9374. },
  9375. enumerable: true,
  9376. configurable: true
  9377. });
  9378. Object.defineProperty(Engine, "REPLACE", {
  9379. get: function () {
  9380. return Engine._REPLACE;
  9381. },
  9382. enumerable: true,
  9383. configurable: true
  9384. });
  9385. Object.defineProperty(Engine, "INCR", {
  9386. get: function () {
  9387. return Engine._INCR;
  9388. },
  9389. enumerable: true,
  9390. configurable: true
  9391. });
  9392. Object.defineProperty(Engine, "DECR", {
  9393. get: function () {
  9394. return Engine._DECR;
  9395. },
  9396. enumerable: true,
  9397. configurable: true
  9398. });
  9399. Object.defineProperty(Engine, "INVERT", {
  9400. get: function () {
  9401. return Engine._INVERT;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Object.defineProperty(Engine, "INCR_WRAP", {
  9407. get: function () {
  9408. return Engine._INCR_WRAP;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. Object.defineProperty(Engine, "DECR_WRAP", {
  9414. get: function () {
  9415. return Engine._DECR_WRAP;
  9416. },
  9417. enumerable: true,
  9418. configurable: true
  9419. });
  9420. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9421. get: function () {
  9422. return Engine._ALPHA_DISABLE;
  9423. },
  9424. enumerable: true,
  9425. configurable: true
  9426. });
  9427. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9428. get: function () {
  9429. return Engine._ALPHA_ONEONE;
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(Engine, "ALPHA_ADD", {
  9435. get: function () {
  9436. return Engine._ALPHA_ADD;
  9437. },
  9438. enumerable: true,
  9439. configurable: true
  9440. });
  9441. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9442. get: function () {
  9443. return Engine._ALPHA_COMBINE;
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9449. get: function () {
  9450. return Engine._ALPHA_SUBTRACT;
  9451. },
  9452. enumerable: true,
  9453. configurable: true
  9454. });
  9455. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9456. get: function () {
  9457. return Engine._ALPHA_MULTIPLY;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9463. get: function () {
  9464. return Engine._ALPHA_MAXIMIZED;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9470. get: function () {
  9471. return Engine._ALPHA_PREMULTIPLIED;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9477. get: function () {
  9478. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9479. },
  9480. enumerable: true,
  9481. configurable: true
  9482. });
  9483. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9484. get: function () {
  9485. return Engine._ALPHA_INTERPOLATE;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9491. get: function () {
  9492. return Engine._ALPHA_SCREENMODE;
  9493. },
  9494. enumerable: true,
  9495. configurable: true
  9496. });
  9497. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9498. get: function () {
  9499. return Engine._DELAYLOADSTATE_NONE;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9505. get: function () {
  9506. return Engine._DELAYLOADSTATE_LOADED;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9512. get: function () {
  9513. return Engine._DELAYLOADSTATE_LOADING;
  9514. },
  9515. enumerable: true,
  9516. configurable: true
  9517. });
  9518. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9519. get: function () {
  9520. return Engine._DELAYLOADSTATE_NOTLOADED;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9526. get: function () {
  9527. return Engine._TEXTUREFORMAT_ALPHA;
  9528. },
  9529. enumerable: true,
  9530. configurable: true
  9531. });
  9532. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9533. get: function () {
  9534. return Engine._TEXTUREFORMAT_LUMINANCE;
  9535. },
  9536. enumerable: true,
  9537. configurable: true
  9538. });
  9539. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9540. get: function () {
  9541. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9542. },
  9543. enumerable: true,
  9544. configurable: true
  9545. });
  9546. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9547. get: function () {
  9548. return Engine._TEXTUREFORMAT_RGB;
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9554. get: function () {
  9555. return Engine._TEXTUREFORMAT_RGBA;
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9561. get: function () {
  9562. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9568. get: function () {
  9569. return Engine._TEXTURETYPE_FLOAT;
  9570. },
  9571. enumerable: true,
  9572. configurable: true
  9573. });
  9574. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9575. get: function () {
  9576. return Engine._TEXTURETYPE_HALF_FLOAT;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9582. get: function () {
  9583. return Engine._SCALEMODE_FLOOR;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9589. get: function () {
  9590. return Engine._SCALEMODE_NEAREST;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9596. get: function () {
  9597. return Engine._SCALEMODE_CEILING;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Engine, "Version", {
  9603. get: function () {
  9604. return "3.2.0-alpha5";
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9610. get: function () {
  9611. return this._vrExclusivePointerMode;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9617. get: function () {
  9618. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9624. get: function () {
  9625. return this._webGLVersion < 2 || this.forcePOTTextures;
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Object.defineProperty(Engine.prototype, "badOS", {
  9631. get: function () {
  9632. return this._badOS;
  9633. },
  9634. enumerable: true,
  9635. configurable: true
  9636. });
  9637. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9638. get: function () {
  9639. return this._badDesktopOS;
  9640. },
  9641. enumerable: true,
  9642. configurable: true
  9643. });
  9644. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9645. get: function () {
  9646. return this._performanceMonitor;
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9652. get: function () {
  9653. return this._texturesSupported;
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9659. get: function () {
  9660. return this._textureFormatInUse;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Engine.prototype, "currentViewport", {
  9666. get: function () {
  9667. return this._cachedViewport;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9673. // Empty texture
  9674. get: function () {
  9675. if (!this._emptyTexture) {
  9676. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9677. }
  9678. return this._emptyTexture;
  9679. },
  9680. enumerable: true,
  9681. configurable: true
  9682. });
  9683. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9684. get: function () {
  9685. if (!this._emptyTexture3D) {
  9686. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9687. }
  9688. return this._emptyTexture3D;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9694. get: function () {
  9695. if (!this._emptyCubeTexture) {
  9696. var faceData = new Uint8Array(4);
  9697. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9698. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9699. }
  9700. return this._emptyCubeTexture;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Engine.prototype._rebuildInternalTextures = function () {
  9706. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9707. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9708. var internalTexture = currentState_1[_i];
  9709. internalTexture._rebuild();
  9710. }
  9711. };
  9712. Engine.prototype._rebuildEffects = function () {
  9713. for (var key in this._compiledEffects) {
  9714. var effect = this._compiledEffects[key];
  9715. effect._prepareEffect();
  9716. }
  9717. BABYLON.Effect.ResetCache();
  9718. };
  9719. Engine.prototype._rebuildBuffers = function () {
  9720. // Index / Vertex
  9721. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9722. var scene = _a[_i];
  9723. scene.resetCachedMaterial();
  9724. scene._rebuildGeometries();
  9725. scene._rebuildTextures();
  9726. }
  9727. // Uniforms
  9728. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9729. var uniformBuffer = _c[_b];
  9730. uniformBuffer._rebuild();
  9731. }
  9732. };
  9733. Engine.prototype._initGLContext = function () {
  9734. // Caps
  9735. this._caps = new EngineCapabilities();
  9736. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9737. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9738. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9739. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9740. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9741. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9742. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9743. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9744. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9745. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9746. // Infos
  9747. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9748. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9749. if (rendererInfo != null) {
  9750. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9751. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9752. }
  9753. if (!this._glVendor) {
  9754. this._glVendor = "Unknown vendor";
  9755. }
  9756. if (!this._glRenderer) {
  9757. this._glRenderer = "Unknown renderer";
  9758. }
  9759. // Constants
  9760. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9761. if (this._gl.RGBA16F !== 0x881A) {
  9762. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9763. }
  9764. if (this._gl.RGBA32F !== 0x8814) {
  9765. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9766. }
  9767. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9768. this._gl.DEPTH24_STENCIL8 = 35056;
  9769. }
  9770. // Extensions
  9771. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9772. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9773. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9774. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9775. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9776. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9777. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9778. 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');
  9779. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9780. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9781. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9782. this._caps.highPrecisionShaderSupported = true;
  9783. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9784. if (this._caps.timerQuery) {
  9785. if (this._webGLVersion === 1) {
  9786. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9787. }
  9788. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9789. }
  9790. // Checks if some of the format renders first to allow the use of webgl inspector.
  9791. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9792. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9793. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9794. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9795. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9796. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9797. if (this._webGLVersion > 1) {
  9798. this._gl.HALF_FLOAT_OES = 0x140B;
  9799. }
  9800. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9801. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9802. // Draw buffers
  9803. if (this._webGLVersion > 1) {
  9804. this._caps.drawBuffersExtension = true;
  9805. }
  9806. else {
  9807. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9808. if (drawBuffersExtension !== null) {
  9809. this._caps.drawBuffersExtension = true;
  9810. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9811. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9812. for (var i = 0; i < 16; i++) {
  9813. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9814. }
  9815. }
  9816. else {
  9817. this._caps.drawBuffersExtension = false;
  9818. }
  9819. }
  9820. // Depth Texture
  9821. if (this._webGLVersion > 1) {
  9822. this._caps.depthTextureExtension = true;
  9823. }
  9824. else {
  9825. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9826. if (depthTextureExtension != null) {
  9827. this._caps.depthTextureExtension = true;
  9828. }
  9829. }
  9830. // Vertex array object
  9831. if (this._webGLVersion > 1) {
  9832. this._caps.vertexArrayObject = true;
  9833. }
  9834. else {
  9835. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9836. if (vertexArrayObjectExtension != null) {
  9837. this._caps.vertexArrayObject = true;
  9838. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9839. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9840. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9841. }
  9842. else {
  9843. this._caps.vertexArrayObject = false;
  9844. }
  9845. }
  9846. // Instances count
  9847. if (this._webGLVersion > 1) {
  9848. this._caps.instancedArrays = true;
  9849. }
  9850. else {
  9851. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9852. if (instanceExtension != null) {
  9853. this._caps.instancedArrays = true;
  9854. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9855. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9856. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9857. }
  9858. else {
  9859. this._caps.instancedArrays = false;
  9860. }
  9861. }
  9862. // Intelligently add supported compressed formats in order to check for.
  9863. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9864. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9865. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9866. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9867. if (this._caps.astc)
  9868. this.texturesSupported.push('-astc.ktx');
  9869. if (this._caps.s3tc)
  9870. this.texturesSupported.push('-dxt.ktx');
  9871. if (this._caps.pvrtc)
  9872. this.texturesSupported.push('-pvrtc.ktx');
  9873. if (this._caps.etc2)
  9874. this.texturesSupported.push('-etc2.ktx');
  9875. if (this._caps.etc1)
  9876. this.texturesSupported.push('-etc1.ktx');
  9877. if (this._gl.getShaderPrecisionFormat) {
  9878. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9879. if (highp) {
  9880. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9881. }
  9882. }
  9883. // Depth buffer
  9884. this.setDepthBuffer(true);
  9885. this.setDepthFunctionToLessOrEqual();
  9886. this.setDepthWrite(true);
  9887. // Texture maps
  9888. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9889. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9890. this._nextFreeTextureSlots.push(slot);
  9891. }
  9892. };
  9893. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9894. get: function () {
  9895. return this._webGLVersion;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9901. /**
  9902. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9903. */
  9904. get: function () {
  9905. return this._isStencilEnable;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Engine.prototype._prepareWorkingCanvas = function () {
  9911. if (this._workingCanvas) {
  9912. return;
  9913. }
  9914. this._workingCanvas = document.createElement("canvas");
  9915. var context = this._workingCanvas.getContext("2d");
  9916. if (context) {
  9917. this._workingContext = context;
  9918. }
  9919. };
  9920. Engine.prototype.resetTextureCache = function () {
  9921. for (var key in this._boundTexturesCache) {
  9922. var boundTexture = this._boundTexturesCache[key];
  9923. if (boundTexture) {
  9924. this._removeDesignatedSlot(boundTexture);
  9925. }
  9926. this._boundTexturesCache[key] = null;
  9927. }
  9928. this._nextFreeTextureSlots = [];
  9929. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9930. this._nextFreeTextureSlots.push(slot);
  9931. }
  9932. this._currentTextureChannel = -1;
  9933. };
  9934. Engine.prototype.isDeterministicLockStep = function () {
  9935. return this._deterministicLockstep;
  9936. };
  9937. Engine.prototype.getLockstepMaxSteps = function () {
  9938. return this._lockstepMaxSteps;
  9939. };
  9940. Engine.prototype.getGlInfo = function () {
  9941. return {
  9942. vendor: this._glVendor,
  9943. renderer: this._glRenderer,
  9944. version: this._glVersion
  9945. };
  9946. };
  9947. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9948. if (useScreen === void 0) { useScreen = false; }
  9949. var viewport = camera.viewport;
  9950. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9951. };
  9952. Engine.prototype.getRenderWidth = function (useScreen) {
  9953. if (useScreen === void 0) { useScreen = false; }
  9954. if (!useScreen && this._currentRenderTarget) {
  9955. return this._currentRenderTarget.width;
  9956. }
  9957. return this._gl.drawingBufferWidth;
  9958. };
  9959. Engine.prototype.getRenderHeight = function (useScreen) {
  9960. if (useScreen === void 0) { useScreen = false; }
  9961. if (!useScreen && this._currentRenderTarget) {
  9962. return this._currentRenderTarget.height;
  9963. }
  9964. return this._gl.drawingBufferHeight;
  9965. };
  9966. Engine.prototype.getRenderingCanvas = function () {
  9967. return this._renderingCanvas;
  9968. };
  9969. Engine.prototype.getRenderingCanvasClientRect = function () {
  9970. if (!this._renderingCanvas) {
  9971. return null;
  9972. }
  9973. return this._renderingCanvas.getBoundingClientRect();
  9974. };
  9975. Engine.prototype.setHardwareScalingLevel = function (level) {
  9976. this._hardwareScalingLevel = level;
  9977. this.resize();
  9978. };
  9979. Engine.prototype.getHardwareScalingLevel = function () {
  9980. return this._hardwareScalingLevel;
  9981. };
  9982. Engine.prototype.getLoadedTexturesCache = function () {
  9983. return this._internalTexturesCache;
  9984. };
  9985. Engine.prototype.getCaps = function () {
  9986. return this._caps;
  9987. };
  9988. Object.defineProperty(Engine.prototype, "drawCalls", {
  9989. /** The number of draw calls submitted last frame */
  9990. get: function () {
  9991. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9992. return 0;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9998. get: function () {
  9999. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10000. return null;
  10001. },
  10002. enumerable: true,
  10003. configurable: true
  10004. });
  10005. Engine.prototype.getDepthFunction = function () {
  10006. return this._depthCullingState.depthFunc;
  10007. };
  10008. Engine.prototype.setDepthFunction = function (depthFunc) {
  10009. this._depthCullingState.depthFunc = depthFunc;
  10010. };
  10011. Engine.prototype.setDepthFunctionToGreater = function () {
  10012. this._depthCullingState.depthFunc = this._gl.GREATER;
  10013. };
  10014. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10015. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10016. };
  10017. Engine.prototype.setDepthFunctionToLess = function () {
  10018. this._depthCullingState.depthFunc = this._gl.LESS;
  10019. };
  10020. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10021. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10022. };
  10023. Engine.prototype.getStencilBuffer = function () {
  10024. return this._stencilState.stencilTest;
  10025. };
  10026. Engine.prototype.setStencilBuffer = function (enable) {
  10027. this._stencilState.stencilTest = enable;
  10028. };
  10029. Engine.prototype.getStencilMask = function () {
  10030. return this._stencilState.stencilMask;
  10031. };
  10032. Engine.prototype.setStencilMask = function (mask) {
  10033. this._stencilState.stencilMask = mask;
  10034. };
  10035. Engine.prototype.getStencilFunction = function () {
  10036. return this._stencilState.stencilFunc;
  10037. };
  10038. Engine.prototype.getStencilFunctionReference = function () {
  10039. return this._stencilState.stencilFuncRef;
  10040. };
  10041. Engine.prototype.getStencilFunctionMask = function () {
  10042. return this._stencilState.stencilFuncMask;
  10043. };
  10044. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10045. this._stencilState.stencilFunc = stencilFunc;
  10046. };
  10047. Engine.prototype.setStencilFunctionReference = function (reference) {
  10048. this._stencilState.stencilFuncRef = reference;
  10049. };
  10050. Engine.prototype.setStencilFunctionMask = function (mask) {
  10051. this._stencilState.stencilFuncMask = mask;
  10052. };
  10053. Engine.prototype.getStencilOperationFail = function () {
  10054. return this._stencilState.stencilOpStencilFail;
  10055. };
  10056. Engine.prototype.getStencilOperationDepthFail = function () {
  10057. return this._stencilState.stencilOpDepthFail;
  10058. };
  10059. Engine.prototype.getStencilOperationPass = function () {
  10060. return this._stencilState.stencilOpStencilDepthPass;
  10061. };
  10062. Engine.prototype.setStencilOperationFail = function (operation) {
  10063. this._stencilState.stencilOpStencilFail = operation;
  10064. };
  10065. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10066. this._stencilState.stencilOpDepthFail = operation;
  10067. };
  10068. Engine.prototype.setStencilOperationPass = function (operation) {
  10069. this._stencilState.stencilOpStencilDepthPass = operation;
  10070. };
  10071. Engine.prototype.setDitheringState = function (value) {
  10072. if (value) {
  10073. this._gl.enable(this._gl.DITHER);
  10074. }
  10075. else {
  10076. this._gl.disable(this._gl.DITHER);
  10077. }
  10078. };
  10079. Engine.prototype.setRasterizerState = function (value) {
  10080. if (value) {
  10081. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10082. }
  10083. else {
  10084. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10085. }
  10086. };
  10087. /**
  10088. * stop executing a render loop function and remove it from the execution array
  10089. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10090. */
  10091. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10092. if (!renderFunction) {
  10093. this._activeRenderLoops = [];
  10094. return;
  10095. }
  10096. var index = this._activeRenderLoops.indexOf(renderFunction);
  10097. if (index >= 0) {
  10098. this._activeRenderLoops.splice(index, 1);
  10099. }
  10100. };
  10101. Engine.prototype._renderLoop = function () {
  10102. if (!this._contextWasLost) {
  10103. var shouldRender = true;
  10104. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10105. shouldRender = false;
  10106. }
  10107. if (shouldRender) {
  10108. // Start new frame
  10109. this.beginFrame();
  10110. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10111. var renderFunction = this._activeRenderLoops[index];
  10112. renderFunction();
  10113. }
  10114. // Present
  10115. this.endFrame();
  10116. }
  10117. }
  10118. if (this._activeRenderLoops.length > 0) {
  10119. // Register new frame
  10120. var requester = null;
  10121. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10122. requester = this._vrDisplay;
  10123. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10124. }
  10125. else {
  10126. this._renderingQueueLaunched = false;
  10127. }
  10128. };
  10129. /**
  10130. * Register and execute a render loop. The engine can have more than one render function.
  10131. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10132. * @example
  10133. * engine.runRenderLoop(function () {
  10134. * scene.render()
  10135. * })
  10136. */
  10137. Engine.prototype.runRenderLoop = function (renderFunction) {
  10138. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10139. return;
  10140. }
  10141. this._activeRenderLoops.push(renderFunction);
  10142. if (!this._renderingQueueLaunched) {
  10143. this._renderingQueueLaunched = true;
  10144. this._bindedRenderFunction = this._renderLoop.bind(this);
  10145. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10146. }
  10147. };
  10148. /**
  10149. * Toggle full screen mode.
  10150. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10151. * @param {any} options - an options object to be sent to the requestFullscreen function
  10152. */
  10153. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10154. if (this.isFullscreen) {
  10155. BABYLON.Tools.ExitFullscreen();
  10156. }
  10157. else {
  10158. this._pointerLockRequested = requestPointerLock;
  10159. if (this._renderingCanvas) {
  10160. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10161. }
  10162. }
  10163. };
  10164. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10165. if (stencil === void 0) { stencil = false; }
  10166. this.applyStates();
  10167. var mode = 0;
  10168. if (backBuffer && color) {
  10169. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10170. mode |= this._gl.COLOR_BUFFER_BIT;
  10171. }
  10172. if (depth) {
  10173. this._gl.clearDepth(1.0);
  10174. mode |= this._gl.DEPTH_BUFFER_BIT;
  10175. }
  10176. if (stencil) {
  10177. this._gl.clearStencil(0);
  10178. mode |= this._gl.STENCIL_BUFFER_BIT;
  10179. }
  10180. this._gl.clear(mode);
  10181. };
  10182. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10183. var gl = this._gl;
  10184. // Save state
  10185. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10186. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10187. // Change state
  10188. gl.enable(gl.SCISSOR_TEST);
  10189. gl.scissor(x, y, width, height);
  10190. // Clear
  10191. this.clear(clearColor, true, true, true);
  10192. // Restore state
  10193. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10194. if (curScissor === true) {
  10195. gl.enable(gl.SCISSOR_TEST);
  10196. }
  10197. else {
  10198. gl.disable(gl.SCISSOR_TEST);
  10199. }
  10200. };
  10201. /**
  10202. * Set the WebGL's viewport
  10203. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10204. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10205. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10206. */
  10207. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10208. var width = requiredWidth || this.getRenderWidth();
  10209. var height = requiredHeight || this.getRenderHeight();
  10210. var x = viewport.x || 0;
  10211. var y = viewport.y || 0;
  10212. this._cachedViewport = viewport;
  10213. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10214. };
  10215. /**
  10216. * Directly set the WebGL Viewport
  10217. * The x, y, width & height are directly passed to the WebGL call
  10218. * @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.
  10219. */
  10220. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10221. var currentViewport = this._cachedViewport;
  10222. this._cachedViewport = null;
  10223. this._gl.viewport(x, y, width, height);
  10224. return currentViewport;
  10225. };
  10226. Engine.prototype.beginFrame = function () {
  10227. this.onBeginFrameObservable.notifyObservers(this);
  10228. this._measureFps();
  10229. };
  10230. Engine.prototype.endFrame = function () {
  10231. //force a flush in case we are using a bad OS.
  10232. if (this._badOS) {
  10233. this.flushFramebuffer();
  10234. }
  10235. //submit frame to the vr device, if enabled
  10236. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10237. // TODO: We should only submit the frame if we read frameData successfully.
  10238. this._vrDisplay.submitFrame();
  10239. }
  10240. this.onEndFrameObservable.notifyObservers(this);
  10241. };
  10242. /**
  10243. * resize the view according to the canvas' size.
  10244. * @example
  10245. * window.addEventListener("resize", function () {
  10246. * engine.resize();
  10247. * });
  10248. */
  10249. Engine.prototype.resize = function () {
  10250. // We're not resizing the size of the canvas while in VR mode & presenting
  10251. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10252. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10253. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10254. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10255. }
  10256. };
  10257. /**
  10258. * force a specific size of the canvas
  10259. * @param {number} width - the new canvas' width
  10260. * @param {number} height - the new canvas' height
  10261. */
  10262. Engine.prototype.setSize = function (width, height) {
  10263. if (!this._renderingCanvas) {
  10264. return;
  10265. }
  10266. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10267. return;
  10268. }
  10269. this._renderingCanvas.width = width;
  10270. this._renderingCanvas.height = height;
  10271. for (var index = 0; index < this.scenes.length; index++) {
  10272. var scene = this.scenes[index];
  10273. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10274. var cam = scene.cameras[camIndex];
  10275. cam._currentRenderId = 0;
  10276. }
  10277. }
  10278. if (this.onResizeObservable.hasObservers) {
  10279. this.onResizeObservable.notifyObservers(this);
  10280. }
  10281. };
  10282. // WebVR functions
  10283. Engine.prototype.isVRDevicePresent = function () {
  10284. return !!this._vrDisplay;
  10285. };
  10286. Engine.prototype.getVRDevice = function () {
  10287. return this._vrDisplay;
  10288. };
  10289. Engine.prototype.initWebVR = function () {
  10290. var _this = this;
  10291. var notifyObservers = function () {
  10292. var eventArgs = {
  10293. vrDisplay: _this._vrDisplay,
  10294. vrSupported: _this._vrSupported
  10295. };
  10296. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10297. };
  10298. if (!this._onVrDisplayConnect) {
  10299. this._onVrDisplayConnect = function (event) {
  10300. _this._vrDisplay = event.display;
  10301. notifyObservers();
  10302. };
  10303. this._onVrDisplayDisconnect = function () {
  10304. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10305. _this._vrDisplay = undefined;
  10306. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10307. notifyObservers();
  10308. };
  10309. this._onVrDisplayPresentChange = function () {
  10310. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10311. };
  10312. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10313. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10314. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10315. }
  10316. this._getVRDisplays(notifyObservers);
  10317. return this.onVRDisplayChangedObservable;
  10318. };
  10319. Engine.prototype.enableVR = function () {
  10320. var _this = this;
  10321. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10322. var onResolved = function () {
  10323. _this.onVRRequestPresentComplete.notifyObservers(true);
  10324. _this._onVRFullScreenTriggered();
  10325. };
  10326. var onRejected = function () {
  10327. _this.onVRRequestPresentComplete.notifyObservers(false);
  10328. };
  10329. this.onVRRequestPresentStart.notifyObservers(this);
  10330. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10331. }
  10332. };
  10333. Engine.prototype.disableVR = function () {
  10334. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10335. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10336. }
  10337. };
  10338. Engine.prototype._getVRDisplays = function (callback) {
  10339. var _this = this;
  10340. var getWebVRDevices = function (devices) {
  10341. _this._vrSupported = true;
  10342. // note that devices may actually be an empty array. This is fine;
  10343. // we expect this._vrDisplay to be undefined in this case.
  10344. return _this._vrDisplay = devices[0];
  10345. };
  10346. if (navigator.getVRDisplays) {
  10347. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10348. // TODO: System CANNOT support WebVR, despite API presence.
  10349. _this._vrSupported = false;
  10350. callback();
  10351. });
  10352. }
  10353. else {
  10354. // TODO: Browser does not support WebVR
  10355. this._vrDisplay = undefined;
  10356. this._vrSupported = false;
  10357. callback();
  10358. }
  10359. };
  10360. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10361. if (this._currentRenderTarget) {
  10362. this.unBindFramebuffer(this._currentRenderTarget);
  10363. }
  10364. this._currentRenderTarget = texture;
  10365. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10366. var gl = this._gl;
  10367. if (texture.isCube) {
  10368. if (faceIndex === undefined) {
  10369. faceIndex = 0;
  10370. }
  10371. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10372. }
  10373. if (this._cachedViewport && !forceFullscreenViewport) {
  10374. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10375. }
  10376. else {
  10377. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10378. }
  10379. this.wipeCaches();
  10380. };
  10381. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10382. if (this._currentFramebuffer !== framebuffer) {
  10383. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10384. this._currentFramebuffer = framebuffer;
  10385. }
  10386. };
  10387. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10388. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10389. this._currentRenderTarget = null;
  10390. // If MSAA, we need to bitblt back to main texture
  10391. var gl = this._gl;
  10392. if (texture._MSAAFramebuffer) {
  10393. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10394. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10395. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10396. }
  10397. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10398. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10399. gl.generateMipmap(gl.TEXTURE_2D);
  10400. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10401. }
  10402. if (onBeforeUnbind) {
  10403. if (texture._MSAAFramebuffer) {
  10404. // Bind the correct framebuffer
  10405. this.bindUnboundFramebuffer(texture._framebuffer);
  10406. }
  10407. onBeforeUnbind();
  10408. }
  10409. this.bindUnboundFramebuffer(null);
  10410. };
  10411. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10412. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10413. this._currentRenderTarget = null;
  10414. // If MSAA, we need to bitblt back to main texture
  10415. var gl = this._gl;
  10416. if (textures[0]._MSAAFramebuffer) {
  10417. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10418. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10419. var attachments = textures[0]._attachments;
  10420. if (!attachments) {
  10421. attachments = new Array(textures.length);
  10422. textures[0]._attachments = attachments;
  10423. }
  10424. for (var i = 0; i < textures.length; i++) {
  10425. var texture = textures[i];
  10426. for (var j = 0; j < attachments.length; j++) {
  10427. attachments[j] = gl.NONE;
  10428. }
  10429. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10430. gl.readBuffer(attachments[i]);
  10431. gl.drawBuffers(attachments);
  10432. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10433. }
  10434. for (var i = 0; i < attachments.length; i++) {
  10435. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10436. }
  10437. gl.drawBuffers(attachments);
  10438. }
  10439. for (var i = 0; i < textures.length; i++) {
  10440. var texture = textures[i];
  10441. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10442. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10443. gl.generateMipmap(gl.TEXTURE_2D);
  10444. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10445. }
  10446. }
  10447. if (onBeforeUnbind) {
  10448. if (textures[0]._MSAAFramebuffer) {
  10449. // Bind the correct framebuffer
  10450. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10451. }
  10452. onBeforeUnbind();
  10453. }
  10454. this.bindUnboundFramebuffer(null);
  10455. };
  10456. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10457. if (texture.generateMipMaps) {
  10458. var gl = this._gl;
  10459. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10460. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10461. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10462. }
  10463. };
  10464. Engine.prototype.flushFramebuffer = function () {
  10465. this._gl.flush();
  10466. };
  10467. Engine.prototype.restoreDefaultFramebuffer = function () {
  10468. if (this._currentRenderTarget) {
  10469. this.unBindFramebuffer(this._currentRenderTarget);
  10470. }
  10471. else {
  10472. this.bindUnboundFramebuffer(null);
  10473. }
  10474. if (this._cachedViewport) {
  10475. this.setViewport(this._cachedViewport);
  10476. }
  10477. this.wipeCaches();
  10478. };
  10479. // UBOs
  10480. Engine.prototype.createUniformBuffer = function (elements) {
  10481. var ubo = this._gl.createBuffer();
  10482. if (!ubo) {
  10483. throw new Error("Unable to create uniform buffer");
  10484. }
  10485. this.bindUniformBuffer(ubo);
  10486. if (elements instanceof Float32Array) {
  10487. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10488. }
  10489. else {
  10490. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10491. }
  10492. this.bindUniformBuffer(null);
  10493. ubo.references = 1;
  10494. return ubo;
  10495. };
  10496. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10497. var ubo = this._gl.createBuffer();
  10498. if (!ubo) {
  10499. throw new Error("Unable to create dynamic uniform buffer");
  10500. }
  10501. this.bindUniformBuffer(ubo);
  10502. if (elements instanceof Float32Array) {
  10503. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10504. }
  10505. else {
  10506. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10507. }
  10508. this.bindUniformBuffer(null);
  10509. ubo.references = 1;
  10510. return ubo;
  10511. };
  10512. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10513. this.bindUniformBuffer(uniformBuffer);
  10514. if (offset === undefined) {
  10515. offset = 0;
  10516. }
  10517. if (count === undefined) {
  10518. if (elements instanceof Float32Array) {
  10519. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10520. }
  10521. else {
  10522. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10523. }
  10524. }
  10525. else {
  10526. if (elements instanceof Float32Array) {
  10527. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10528. }
  10529. else {
  10530. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10531. }
  10532. }
  10533. this.bindUniformBuffer(null);
  10534. };
  10535. // VBOs
  10536. Engine.prototype._resetVertexBufferBinding = function () {
  10537. this.bindArrayBuffer(null);
  10538. this._cachedVertexBuffers = null;
  10539. };
  10540. Engine.prototype.createVertexBuffer = function (vertices) {
  10541. var vbo = this._gl.createBuffer();
  10542. if (!vbo) {
  10543. throw new Error("Unable to create vertex buffer");
  10544. }
  10545. this.bindArrayBuffer(vbo);
  10546. if (vertices instanceof Float32Array) {
  10547. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10548. }
  10549. else {
  10550. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10551. }
  10552. this._resetVertexBufferBinding();
  10553. vbo.references = 1;
  10554. return vbo;
  10555. };
  10556. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10557. var vbo = this._gl.createBuffer();
  10558. if (!vbo) {
  10559. throw new Error("Unable to create dynamic vertex buffer");
  10560. }
  10561. this.bindArrayBuffer(vbo);
  10562. if (vertices instanceof Float32Array) {
  10563. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10564. }
  10565. else {
  10566. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10567. }
  10568. this._resetVertexBufferBinding();
  10569. vbo.references = 1;
  10570. return vbo;
  10571. };
  10572. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10573. if (offset === void 0) { offset = 0; }
  10574. // Force cache update
  10575. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10576. this.bindIndexBuffer(indexBuffer);
  10577. var arrayBuffer;
  10578. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10579. arrayBuffer = indices;
  10580. }
  10581. else {
  10582. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10583. }
  10584. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10585. this._resetIndexBufferBinding();
  10586. };
  10587. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10588. this.bindArrayBuffer(vertexBuffer);
  10589. if (offset === undefined) {
  10590. offset = 0;
  10591. }
  10592. if (count === undefined) {
  10593. if (vertices instanceof Float32Array) {
  10594. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10595. }
  10596. else {
  10597. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10598. }
  10599. }
  10600. else {
  10601. if (vertices instanceof Float32Array) {
  10602. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10603. }
  10604. else {
  10605. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10606. }
  10607. }
  10608. this._resetVertexBufferBinding();
  10609. };
  10610. Engine.prototype._resetIndexBufferBinding = function () {
  10611. this.bindIndexBuffer(null);
  10612. this._cachedIndexBuffer = null;
  10613. };
  10614. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10615. var vbo = this._gl.createBuffer();
  10616. if (!vbo) {
  10617. throw new Error("Unable to create index buffer");
  10618. }
  10619. this.bindIndexBuffer(vbo);
  10620. // Check for 32 bits indices
  10621. var arrayBuffer;
  10622. var need32Bits = false;
  10623. if (indices instanceof Uint16Array) {
  10624. arrayBuffer = indices;
  10625. }
  10626. else {
  10627. //check 32 bit support
  10628. if (this._caps.uintIndices) {
  10629. if (indices instanceof Uint32Array) {
  10630. arrayBuffer = indices;
  10631. need32Bits = true;
  10632. }
  10633. else {
  10634. //number[] or Int32Array, check if 32 bit is necessary
  10635. for (var index = 0; index < indices.length; index++) {
  10636. if (indices[index] > 65535) {
  10637. need32Bits = true;
  10638. break;
  10639. }
  10640. }
  10641. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10642. }
  10643. }
  10644. else {
  10645. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10646. arrayBuffer = new Uint16Array(indices);
  10647. }
  10648. }
  10649. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10650. this._resetIndexBufferBinding();
  10651. vbo.references = 1;
  10652. vbo.is32Bits = need32Bits;
  10653. return vbo;
  10654. };
  10655. Engine.prototype.bindArrayBuffer = function (buffer) {
  10656. if (!this._vaoRecordInProgress) {
  10657. this._unbindVertexArrayObject();
  10658. }
  10659. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10660. };
  10661. Engine.prototype.bindUniformBuffer = function (buffer) {
  10662. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10663. };
  10664. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10665. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10666. };
  10667. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10668. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10669. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10670. };
  10671. ;
  10672. Engine.prototype.bindIndexBuffer = function (buffer) {
  10673. if (!this._vaoRecordInProgress) {
  10674. this._unbindVertexArrayObject();
  10675. }
  10676. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10677. };
  10678. Engine.prototype.bindBuffer = function (buffer, target) {
  10679. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10680. this._gl.bindBuffer(target, buffer);
  10681. this._currentBoundBuffer[target] = buffer;
  10682. }
  10683. };
  10684. Engine.prototype.updateArrayBuffer = function (data) {
  10685. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10686. };
  10687. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10688. var pointer = this._currentBufferPointers[indx];
  10689. var changed = false;
  10690. if (!pointer.active) {
  10691. changed = true;
  10692. pointer.active = true;
  10693. pointer.index = indx;
  10694. pointer.size = size;
  10695. pointer.type = type;
  10696. pointer.normalized = normalized;
  10697. pointer.stride = stride;
  10698. pointer.offset = offset;
  10699. pointer.buffer = buffer;
  10700. }
  10701. else {
  10702. if (pointer.buffer !== buffer) {
  10703. pointer.buffer = buffer;
  10704. changed = true;
  10705. }
  10706. if (pointer.size !== size) {
  10707. pointer.size = size;
  10708. changed = true;
  10709. }
  10710. if (pointer.type !== type) {
  10711. pointer.type = type;
  10712. changed = true;
  10713. }
  10714. if (pointer.normalized !== normalized) {
  10715. pointer.normalized = normalized;
  10716. changed = true;
  10717. }
  10718. if (pointer.stride !== stride) {
  10719. pointer.stride = stride;
  10720. changed = true;
  10721. }
  10722. if (pointer.offset !== offset) {
  10723. pointer.offset = offset;
  10724. changed = true;
  10725. }
  10726. }
  10727. if (changed || this._vaoRecordInProgress) {
  10728. this.bindArrayBuffer(buffer);
  10729. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10730. }
  10731. };
  10732. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10733. if (indexBuffer == null) {
  10734. return;
  10735. }
  10736. if (this._cachedIndexBuffer !== indexBuffer) {
  10737. this._cachedIndexBuffer = indexBuffer;
  10738. this.bindIndexBuffer(indexBuffer);
  10739. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10740. }
  10741. };
  10742. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10743. var attributes = effect.getAttributesNames();
  10744. if (!this._vaoRecordInProgress) {
  10745. this._unbindVertexArrayObject();
  10746. }
  10747. this.unbindAllAttributes();
  10748. for (var index = 0; index < attributes.length; index++) {
  10749. var order = effect.getAttributeLocation(index);
  10750. if (order >= 0) {
  10751. var vertexBuffer = vertexBuffers[attributes[index]];
  10752. if (!vertexBuffer) {
  10753. continue;
  10754. }
  10755. this._gl.enableVertexAttribArray(order);
  10756. if (!this._vaoRecordInProgress) {
  10757. this._vertexAttribArraysEnabled[order] = true;
  10758. }
  10759. var buffer = vertexBuffer.getBuffer();
  10760. if (buffer) {
  10761. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10762. if (vertexBuffer.getIsInstanced()) {
  10763. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10764. if (!this._vaoRecordInProgress) {
  10765. this._currentInstanceLocations.push(order);
  10766. this._currentInstanceBuffers.push(buffer);
  10767. }
  10768. }
  10769. }
  10770. }
  10771. }
  10772. };
  10773. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10774. var vao = this._gl.createVertexArray();
  10775. this._vaoRecordInProgress = true;
  10776. this._gl.bindVertexArray(vao);
  10777. this._mustWipeVertexAttributes = true;
  10778. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10779. this.bindIndexBuffer(indexBuffer);
  10780. this._vaoRecordInProgress = false;
  10781. this._gl.bindVertexArray(null);
  10782. return vao;
  10783. };
  10784. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10785. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10786. this._cachedVertexArrayObject = vertexArrayObject;
  10787. this._gl.bindVertexArray(vertexArrayObject);
  10788. this._cachedVertexBuffers = null;
  10789. this._cachedIndexBuffer = null;
  10790. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10791. this._mustWipeVertexAttributes = true;
  10792. }
  10793. };
  10794. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10795. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10796. this._cachedVertexBuffers = vertexBuffer;
  10797. this._cachedEffectForVertexBuffers = effect;
  10798. var attributesCount = effect.getAttributesCount();
  10799. this._unbindVertexArrayObject();
  10800. this.unbindAllAttributes();
  10801. var offset = 0;
  10802. for (var index = 0; index < attributesCount; index++) {
  10803. if (index < vertexDeclaration.length) {
  10804. var order = effect.getAttributeLocation(index);
  10805. if (order >= 0) {
  10806. this._gl.enableVertexAttribArray(order);
  10807. this._vertexAttribArraysEnabled[order] = true;
  10808. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10809. }
  10810. offset += vertexDeclaration[index] * 4;
  10811. }
  10812. }
  10813. }
  10814. this._bindIndexBufferWithCache(indexBuffer);
  10815. };
  10816. Engine.prototype._unbindVertexArrayObject = function () {
  10817. if (!this._cachedVertexArrayObject) {
  10818. return;
  10819. }
  10820. this._cachedVertexArrayObject = null;
  10821. this._gl.bindVertexArray(null);
  10822. };
  10823. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10824. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10825. this._cachedVertexBuffers = vertexBuffers;
  10826. this._cachedEffectForVertexBuffers = effect;
  10827. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10828. }
  10829. this._bindIndexBufferWithCache(indexBuffer);
  10830. };
  10831. Engine.prototype.unbindInstanceAttributes = function () {
  10832. var boundBuffer;
  10833. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10834. var instancesBuffer = this._currentInstanceBuffers[i];
  10835. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10836. boundBuffer = instancesBuffer;
  10837. this.bindArrayBuffer(instancesBuffer);
  10838. }
  10839. var offsetLocation = this._currentInstanceLocations[i];
  10840. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10841. }
  10842. this._currentInstanceBuffers.length = 0;
  10843. this._currentInstanceLocations.length = 0;
  10844. };
  10845. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10846. this._gl.deleteVertexArray(vao);
  10847. };
  10848. Engine.prototype._releaseBuffer = function (buffer) {
  10849. buffer.references--;
  10850. if (buffer.references === 0) {
  10851. this._gl.deleteBuffer(buffer);
  10852. return true;
  10853. }
  10854. return false;
  10855. };
  10856. Engine.prototype.createInstancesBuffer = function (capacity) {
  10857. var buffer = this._gl.createBuffer();
  10858. if (!buffer) {
  10859. throw new Error("Unable to create instance buffer");
  10860. }
  10861. buffer.capacity = capacity;
  10862. this.bindArrayBuffer(buffer);
  10863. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10864. return buffer;
  10865. };
  10866. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10867. this._gl.deleteBuffer(buffer);
  10868. };
  10869. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10870. this.bindArrayBuffer(instancesBuffer);
  10871. if (data) {
  10872. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10873. }
  10874. if (offsetLocations[0].index !== undefined) {
  10875. var stride = 0;
  10876. for (var i = 0; i < offsetLocations.length; i++) {
  10877. var ai = offsetLocations[i];
  10878. stride += ai.attributeSize * 4;
  10879. }
  10880. for (var i = 0; i < offsetLocations.length; i++) {
  10881. var ai = offsetLocations[i];
  10882. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10883. this._gl.enableVertexAttribArray(ai.index);
  10884. this._vertexAttribArraysEnabled[ai.index] = true;
  10885. }
  10886. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10887. this._gl.vertexAttribDivisor(ai.index, 1);
  10888. this._currentInstanceLocations.push(ai.index);
  10889. this._currentInstanceBuffers.push(instancesBuffer);
  10890. }
  10891. }
  10892. else {
  10893. for (var index = 0; index < 4; index++) {
  10894. var offsetLocation = offsetLocations[index];
  10895. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10896. this._gl.enableVertexAttribArray(offsetLocation);
  10897. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10898. }
  10899. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10900. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10901. this._currentInstanceLocations.push(offsetLocation);
  10902. this._currentInstanceBuffers.push(instancesBuffer);
  10903. }
  10904. }
  10905. };
  10906. Engine.prototype.applyStates = function () {
  10907. this._depthCullingState.apply(this._gl);
  10908. this._stencilState.apply(this._gl);
  10909. this._alphaState.apply(this._gl);
  10910. };
  10911. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10912. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10913. };
  10914. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10915. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10916. };
  10917. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10918. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10919. };
  10920. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10921. // Apply states
  10922. this.applyStates();
  10923. this._drawCalls.addCount(1, false);
  10924. // Render
  10925. var drawMode = this.DrawMode(fillMode);
  10926. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10927. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10928. if (instancesCount) {
  10929. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10930. }
  10931. else {
  10932. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10933. }
  10934. };
  10935. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10936. // Apply states
  10937. this.applyStates();
  10938. this._drawCalls.addCount(1, false);
  10939. var drawMode = this.DrawMode(fillMode);
  10940. if (instancesCount) {
  10941. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10942. }
  10943. else {
  10944. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10945. }
  10946. };
  10947. Engine.prototype.DrawMode = function (fillMode) {
  10948. switch (fillMode) {
  10949. // Triangle views
  10950. case BABYLON.Material.TriangleFillMode:
  10951. return this._gl.TRIANGLES;
  10952. case BABYLON.Material.PointFillMode:
  10953. return this._gl.POINTS;
  10954. case BABYLON.Material.WireFrameFillMode:
  10955. return this._gl.LINES;
  10956. // Draw modes
  10957. case BABYLON.Material.PointListDrawMode:
  10958. return this._gl.POINTS;
  10959. case BABYLON.Material.LineListDrawMode:
  10960. return this._gl.LINES;
  10961. case BABYLON.Material.LineLoopDrawMode:
  10962. return this._gl.LINE_LOOP;
  10963. case BABYLON.Material.LineStripDrawMode:
  10964. return this._gl.LINE_STRIP;
  10965. case BABYLON.Material.TriangleStripDrawMode:
  10966. return this._gl.TRIANGLE_STRIP;
  10967. case BABYLON.Material.TriangleFanDrawMode:
  10968. return this._gl.TRIANGLE_FAN;
  10969. default:
  10970. return this._gl.TRIANGLES;
  10971. }
  10972. };
  10973. // Shaders
  10974. Engine.prototype._releaseEffect = function (effect) {
  10975. if (this._compiledEffects[effect._key]) {
  10976. delete this._compiledEffects[effect._key];
  10977. this._deleteProgram(effect.getProgram());
  10978. }
  10979. };
  10980. Engine.prototype._deleteProgram = function (program) {
  10981. if (program) {
  10982. program.__SPECTOR_rebuildProgram = null;
  10983. if (program.transformFeedback) {
  10984. this.deleteTransformFeedback(program.transformFeedback);
  10985. program.transformFeedback = null;
  10986. }
  10987. this._gl.deleteProgram(program);
  10988. }
  10989. };
  10990. /**
  10991. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10992. * @param samplers An array of string used to represent textures
  10993. */
  10994. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10995. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10996. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10997. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10998. if (this._compiledEffects[name]) {
  10999. var compiledEffect = this._compiledEffects[name];
  11000. if (onCompiled && compiledEffect.isReady()) {
  11001. onCompiled(compiledEffect);
  11002. }
  11003. return compiledEffect;
  11004. }
  11005. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11006. effect._key = name;
  11007. this._compiledEffects[name] = effect;
  11008. return effect;
  11009. };
  11010. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11011. if (uniformsNames === void 0) { uniformsNames = []; }
  11012. if (samplers === void 0) { samplers = []; }
  11013. if (defines === void 0) { defines = ""; }
  11014. return this.createEffect({
  11015. vertex: "particles",
  11016. fragmentElement: fragmentName
  11017. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11018. };
  11019. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11020. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11021. context = context || this._gl;
  11022. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11023. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11024. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11025. };
  11026. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11027. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11028. context = context || this._gl;
  11029. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11030. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11031. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11032. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11033. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11034. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11035. return program;
  11036. };
  11037. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11038. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11039. var shaderProgram = context.createProgram();
  11040. if (!shaderProgram) {
  11041. throw new Error("Unable to create program");
  11042. }
  11043. context.attachShader(shaderProgram, vertexShader);
  11044. context.attachShader(shaderProgram, fragmentShader);
  11045. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11046. var transformFeedback = this.createTransformFeedback();
  11047. this.bindTransformFeedback(transformFeedback);
  11048. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11049. shaderProgram.transformFeedback = transformFeedback;
  11050. }
  11051. context.linkProgram(shaderProgram);
  11052. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11053. this.bindTransformFeedback(null);
  11054. }
  11055. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11056. if (!linked) {
  11057. context.validateProgram(shaderProgram);
  11058. var error = context.getProgramInfoLog(shaderProgram);
  11059. if (error) {
  11060. throw new Error(error);
  11061. }
  11062. }
  11063. context.deleteShader(vertexShader);
  11064. context.deleteShader(fragmentShader);
  11065. return shaderProgram;
  11066. };
  11067. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11068. var results = new Array();
  11069. for (var index = 0; index < uniformsNames.length; index++) {
  11070. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11071. }
  11072. return results;
  11073. };
  11074. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11075. var results = [];
  11076. for (var index = 0; index < attributesNames.length; index++) {
  11077. try {
  11078. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11079. }
  11080. catch (e) {
  11081. results.push(-1);
  11082. }
  11083. }
  11084. return results;
  11085. };
  11086. Engine.prototype.enableEffect = function (effect) {
  11087. if (!effect) {
  11088. return;
  11089. }
  11090. // Use program
  11091. this.bindSamplers(effect);
  11092. this._currentEffect = effect;
  11093. if (effect.onBind) {
  11094. effect.onBind(effect);
  11095. }
  11096. effect.onBindObservable.notifyObservers(effect);
  11097. };
  11098. Engine.prototype.setIntArray = function (uniform, array) {
  11099. if (!uniform)
  11100. return;
  11101. this._gl.uniform1iv(uniform, array);
  11102. };
  11103. Engine.prototype.setIntArray2 = function (uniform, array) {
  11104. if (!uniform || array.length % 2 !== 0)
  11105. return;
  11106. this._gl.uniform2iv(uniform, array);
  11107. };
  11108. Engine.prototype.setIntArray3 = function (uniform, array) {
  11109. if (!uniform || array.length % 3 !== 0)
  11110. return;
  11111. this._gl.uniform3iv(uniform, array);
  11112. };
  11113. Engine.prototype.setIntArray4 = function (uniform, array) {
  11114. if (!uniform || array.length % 4 !== 0)
  11115. return;
  11116. this._gl.uniform4iv(uniform, array);
  11117. };
  11118. Engine.prototype.setFloatArray = function (uniform, array) {
  11119. if (!uniform)
  11120. return;
  11121. this._gl.uniform1fv(uniform, array);
  11122. };
  11123. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11124. if (!uniform || array.length % 2 !== 0)
  11125. return;
  11126. this._gl.uniform2fv(uniform, array);
  11127. };
  11128. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11129. if (!uniform || array.length % 3 !== 0)
  11130. return;
  11131. this._gl.uniform3fv(uniform, array);
  11132. };
  11133. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11134. if (!uniform || array.length % 4 !== 0)
  11135. return;
  11136. this._gl.uniform4fv(uniform, array);
  11137. };
  11138. Engine.prototype.setArray = function (uniform, array) {
  11139. if (!uniform)
  11140. return;
  11141. this._gl.uniform1fv(uniform, array);
  11142. };
  11143. Engine.prototype.setArray2 = function (uniform, array) {
  11144. if (!uniform || array.length % 2 !== 0)
  11145. return;
  11146. this._gl.uniform2fv(uniform, array);
  11147. };
  11148. Engine.prototype.setArray3 = function (uniform, array) {
  11149. if (!uniform || array.length % 3 !== 0)
  11150. return;
  11151. this._gl.uniform3fv(uniform, array);
  11152. };
  11153. Engine.prototype.setArray4 = function (uniform, array) {
  11154. if (!uniform || array.length % 4 !== 0)
  11155. return;
  11156. this._gl.uniform4fv(uniform, array);
  11157. };
  11158. Engine.prototype.setMatrices = function (uniform, matrices) {
  11159. if (!uniform)
  11160. return;
  11161. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11162. };
  11163. Engine.prototype.setMatrix = function (uniform, matrix) {
  11164. if (!uniform)
  11165. return;
  11166. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11167. };
  11168. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11169. if (!uniform)
  11170. return;
  11171. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11172. };
  11173. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11174. if (!uniform)
  11175. return;
  11176. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11177. };
  11178. Engine.prototype.setInt = function (uniform, value) {
  11179. if (!uniform)
  11180. return;
  11181. this._gl.uniform1i(uniform, value);
  11182. };
  11183. Engine.prototype.setFloat = function (uniform, value) {
  11184. if (!uniform)
  11185. return;
  11186. this._gl.uniform1f(uniform, value);
  11187. };
  11188. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11189. if (!uniform)
  11190. return;
  11191. this._gl.uniform2f(uniform, x, y);
  11192. };
  11193. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11194. if (!uniform)
  11195. return;
  11196. this._gl.uniform3f(uniform, x, y, z);
  11197. };
  11198. Engine.prototype.setBool = function (uniform, bool) {
  11199. if (!uniform)
  11200. return;
  11201. this._gl.uniform1i(uniform, bool);
  11202. };
  11203. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11204. if (!uniform)
  11205. return;
  11206. this._gl.uniform4f(uniform, x, y, z, w);
  11207. };
  11208. Engine.prototype.setColor3 = function (uniform, color3) {
  11209. if (!uniform)
  11210. return;
  11211. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11212. };
  11213. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11214. if (!uniform)
  11215. return;
  11216. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11217. };
  11218. // States
  11219. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11220. if (zOffset === void 0) { zOffset = 0; }
  11221. if (reverseSide === void 0) { reverseSide = false; }
  11222. // Culling
  11223. if (this._depthCullingState.cull !== culling || force) {
  11224. this._depthCullingState.cull = culling;
  11225. }
  11226. // Cull face
  11227. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11228. if (this._depthCullingState.cullFace !== cullFace || force) {
  11229. this._depthCullingState.cullFace = cullFace;
  11230. }
  11231. // Z offset
  11232. this.setZOffset(zOffset);
  11233. // Front face
  11234. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11235. if (this._depthCullingState.frontFace !== frontFace || force) {
  11236. this._depthCullingState.frontFace = frontFace;
  11237. }
  11238. };
  11239. Engine.prototype.setZOffset = function (value) {
  11240. this._depthCullingState.zOffset = value;
  11241. };
  11242. Engine.prototype.getZOffset = function () {
  11243. return this._depthCullingState.zOffset;
  11244. };
  11245. Engine.prototype.setDepthBuffer = function (enable) {
  11246. this._depthCullingState.depthTest = enable;
  11247. };
  11248. Engine.prototype.getDepthWrite = function () {
  11249. return this._depthCullingState.depthMask;
  11250. };
  11251. Engine.prototype.setDepthWrite = function (enable) {
  11252. this._depthCullingState.depthMask = enable;
  11253. };
  11254. Engine.prototype.setColorWrite = function (enable) {
  11255. this._gl.colorMask(enable, enable, enable, enable);
  11256. this._colorWrite = enable;
  11257. };
  11258. Engine.prototype.getColorWrite = function () {
  11259. return this._colorWrite;
  11260. };
  11261. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11262. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11263. };
  11264. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11265. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11266. if (this._alphaMode === mode) {
  11267. return;
  11268. }
  11269. switch (mode) {
  11270. case Engine.ALPHA_DISABLE:
  11271. this._alphaState.alphaBlend = false;
  11272. break;
  11273. case Engine.ALPHA_PREMULTIPLIED:
  11274. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11275. this._alphaState.alphaBlend = true;
  11276. break;
  11277. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11278. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11279. this._alphaState.alphaBlend = true;
  11280. break;
  11281. case Engine.ALPHA_COMBINE:
  11282. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11283. this._alphaState.alphaBlend = true;
  11284. break;
  11285. case Engine.ALPHA_ONEONE:
  11286. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11287. this._alphaState.alphaBlend = true;
  11288. break;
  11289. case Engine.ALPHA_ADD:
  11290. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11291. this._alphaState.alphaBlend = true;
  11292. break;
  11293. case Engine.ALPHA_SUBTRACT:
  11294. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11295. this._alphaState.alphaBlend = true;
  11296. break;
  11297. case Engine.ALPHA_MULTIPLY:
  11298. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11299. this._alphaState.alphaBlend = true;
  11300. break;
  11301. case Engine.ALPHA_MAXIMIZED:
  11302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11303. this._alphaState.alphaBlend = true;
  11304. break;
  11305. case Engine.ALPHA_INTERPOLATE:
  11306. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11307. this._alphaState.alphaBlend = true;
  11308. break;
  11309. case Engine.ALPHA_SCREENMODE:
  11310. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11311. this._alphaState.alphaBlend = true;
  11312. break;
  11313. }
  11314. if (!noDepthWriteChange) {
  11315. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11316. }
  11317. this._alphaMode = mode;
  11318. };
  11319. Engine.prototype.getAlphaMode = function () {
  11320. return this._alphaMode;
  11321. };
  11322. // Textures
  11323. Engine.prototype.wipeCaches = function (bruteForce) {
  11324. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11325. return;
  11326. }
  11327. this._currentEffect = null;
  11328. // 6/8/2017: deltakosh: Should not be required anymore.
  11329. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11330. if (bruteForce) {
  11331. this.resetTextureCache();
  11332. this._currentProgram = null;
  11333. this._stencilState.reset();
  11334. this._depthCullingState.reset();
  11335. this.setDepthFunctionToLessOrEqual();
  11336. this._alphaState.reset();
  11337. }
  11338. this._resetVertexBufferBinding();
  11339. this._cachedIndexBuffer = null;
  11340. this._cachedEffectForVertexBuffers = null;
  11341. this._unbindVertexArrayObject();
  11342. this.bindIndexBuffer(null);
  11343. };
  11344. /**
  11345. * Set the compressed texture format to use, based on the formats you have, and the formats
  11346. * supported by the hardware / browser.
  11347. *
  11348. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11349. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11350. * to API arguments needed to compressed textures. This puts the burden on the container
  11351. * generator to house the arcane code for determining these for current & future formats.
  11352. *
  11353. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11354. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11355. *
  11356. * Note: The result of this call is not taken into account when a texture is base64.
  11357. *
  11358. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11359. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11360. *
  11361. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11362. * @returns The extension selected.
  11363. */
  11364. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11365. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11366. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11367. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11368. return this._textureFormatInUse = this._texturesSupported[i];
  11369. }
  11370. }
  11371. }
  11372. // actively set format to nothing, to allow this to be called more than once
  11373. // and possibly fail the 2nd time
  11374. this._textureFormatInUse = null;
  11375. return null;
  11376. };
  11377. Engine.prototype._createTexture = function () {
  11378. var texture = this._gl.createTexture();
  11379. if (!texture) {
  11380. throw new Error("Unable to create texture");
  11381. }
  11382. return texture;
  11383. };
  11384. /**
  11385. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11386. * @param {string} urlArg- This contains one of the following:
  11387. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11388. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11389. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11390. *
  11391. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11392. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11393. * @param {Scene} scene- Needed for loading to the correct scene.
  11394. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11395. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11396. * @param {callback} onError- Optional callback to be called upon failure.
  11397. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11398. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11399. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11400. *
  11401. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11402. */
  11403. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11404. var _this = this;
  11405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11406. if (onLoad === void 0) { onLoad = null; }
  11407. if (onError === void 0) { onError = null; }
  11408. if (buffer === void 0) { buffer = null; }
  11409. if (fallBack === void 0) { fallBack = null; }
  11410. if (format === void 0) { format = null; }
  11411. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11412. var fromData = url.substr(0, 5) === "data:";
  11413. var fromBlob = url.substr(0, 5) === "blob:";
  11414. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11415. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11416. // establish the file extension, if possible
  11417. var lastDot = url.lastIndexOf('.');
  11418. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11419. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11420. var isTGA = (extension === ".tga");
  11421. // determine if a ktx file should be substituted
  11422. var isKTX = false;
  11423. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11424. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11425. isKTX = true;
  11426. }
  11427. if (scene) {
  11428. scene._addPendingData(texture);
  11429. }
  11430. texture.url = url;
  11431. texture.generateMipMaps = !noMipmap;
  11432. texture.samplingMode = samplingMode;
  11433. texture.invertY = invertY;
  11434. if (!this._doNotHandleContextLost) {
  11435. // Keep a link to the buffer only if we plan to handle context lost
  11436. texture._buffer = buffer;
  11437. }
  11438. var onLoadObserver = null;
  11439. if (onLoad && !fallBack) {
  11440. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11441. }
  11442. if (!fallBack)
  11443. this._internalTexturesCache.push(texture);
  11444. var onerror = function (message, exception) {
  11445. if (scene) {
  11446. scene._removePendingData(texture);
  11447. }
  11448. if (onLoadObserver) {
  11449. texture.onLoadedObservable.remove(onLoadObserver);
  11450. }
  11451. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11452. if (isKTX) {
  11453. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11454. }
  11455. else if (BABYLON.Tools.UseFallbackTexture) {
  11456. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11457. }
  11458. if (onError) {
  11459. onError(message || "Unknown error", exception);
  11460. }
  11461. };
  11462. var callback = null;
  11463. // processing for non-image formats
  11464. if (isKTX || isTGA || isDDS) {
  11465. if (isKTX) {
  11466. callback = function (data) {
  11467. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11468. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11469. ktx.uploadLevels(_this._gl, !noMipmap);
  11470. return false;
  11471. }, samplingMode);
  11472. };
  11473. }
  11474. else if (isTGA) {
  11475. callback = function (arrayBuffer) {
  11476. var data = new Uint8Array(arrayBuffer);
  11477. var header = BABYLON.TGATools.GetTGAHeader(data);
  11478. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11479. BABYLON.TGATools.UploadContent(_this._gl, data);
  11480. return false;
  11481. }, samplingMode);
  11482. };
  11483. }
  11484. else if (isDDS) {
  11485. callback = function (data) {
  11486. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11487. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11488. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11489. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11490. return false;
  11491. }, samplingMode);
  11492. };
  11493. }
  11494. if (!buffer) {
  11495. this._loadFile(url, function (data) {
  11496. if (callback) {
  11497. callback(data);
  11498. }
  11499. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11500. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11501. });
  11502. }
  11503. else {
  11504. if (callback) {
  11505. callback(buffer);
  11506. }
  11507. }
  11508. // image format processing
  11509. }
  11510. else {
  11511. var onload = function (img) {
  11512. if (fromBlob && !_this._doNotHandleContextLost) {
  11513. // We need to store the image if we need to rebuild the texture
  11514. // in case of a webgl context lost
  11515. texture._buffer = img;
  11516. }
  11517. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11518. var gl = _this._gl;
  11519. var isPot = (img.width === potWidth && img.height === potHeight);
  11520. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11521. if (isPot) {
  11522. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11523. return false;
  11524. }
  11525. // Using shaders to rescale because canvas.drawImage is lossy
  11526. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11527. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11528. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11533. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11534. _this._releaseTexture(source);
  11535. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11536. continuationCallback();
  11537. });
  11538. return true;
  11539. }, samplingMode);
  11540. };
  11541. if (!fromData || isBase64)
  11542. if (buffer instanceof HTMLImageElement) {
  11543. onload(buffer);
  11544. }
  11545. else {
  11546. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11547. }
  11548. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11549. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11550. else
  11551. onload(buffer);
  11552. }
  11553. return texture;
  11554. };
  11555. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11556. var _this = this;
  11557. var rtt = this.createRenderTargetTexture({
  11558. width: destination.width,
  11559. height: destination.height,
  11560. }, {
  11561. generateMipMaps: false,
  11562. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11563. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11564. generateDepthBuffer: false,
  11565. generateStencilBuffer: false
  11566. });
  11567. if (!this._rescalePostProcess) {
  11568. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11569. }
  11570. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11571. _this._rescalePostProcess.onApply = function (effect) {
  11572. effect._bindTexture("textureSampler", source);
  11573. };
  11574. var hostingScene = scene;
  11575. if (!hostingScene) {
  11576. hostingScene = _this.scenes[_this.scenes.length - 1];
  11577. }
  11578. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11579. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11580. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11581. _this.unBindFramebuffer(rtt);
  11582. _this._releaseTexture(rtt);
  11583. if (onComplete) {
  11584. onComplete();
  11585. }
  11586. });
  11587. };
  11588. Engine.prototype._getInternalFormat = function (format) {
  11589. var internalFormat = this._gl.RGBA;
  11590. switch (format) {
  11591. case Engine.TEXTUREFORMAT_ALPHA:
  11592. internalFormat = this._gl.ALPHA;
  11593. break;
  11594. case Engine.TEXTUREFORMAT_LUMINANCE:
  11595. internalFormat = this._gl.LUMINANCE;
  11596. break;
  11597. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11598. internalFormat = this._gl.LUMINANCE_ALPHA;
  11599. break;
  11600. case Engine.TEXTUREFORMAT_RGB:
  11601. internalFormat = this._gl.RGB;
  11602. break;
  11603. case Engine.TEXTUREFORMAT_RGBA:
  11604. internalFormat = this._gl.RGBA;
  11605. break;
  11606. }
  11607. return internalFormat;
  11608. };
  11609. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11610. if (compression === void 0) { compression = null; }
  11611. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11612. if (!texture) {
  11613. return;
  11614. }
  11615. var internalFormat = this._getInternalFormat(format);
  11616. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11617. var textureType = this._getWebGLTextureType(type);
  11618. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11619. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11620. if (!this._doNotHandleContextLost) {
  11621. texture._bufferView = data;
  11622. texture.format = format;
  11623. texture.type = type;
  11624. texture.invertY = invertY;
  11625. texture._compression = compression;
  11626. }
  11627. if (texture.width % 4 !== 0) {
  11628. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11629. }
  11630. if (compression && data) {
  11631. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11632. }
  11633. else {
  11634. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11635. }
  11636. if (texture.generateMipMaps) {
  11637. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11638. }
  11639. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11640. // this.resetTextureCache();
  11641. texture.isReady = true;
  11642. };
  11643. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11644. if (compression === void 0) { compression = null; }
  11645. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11646. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11647. texture.baseWidth = width;
  11648. texture.baseHeight = height;
  11649. texture.width = width;
  11650. texture.height = height;
  11651. texture.format = format;
  11652. texture.generateMipMaps = generateMipMaps;
  11653. texture.samplingMode = samplingMode;
  11654. texture.invertY = invertY;
  11655. texture._compression = compression;
  11656. texture.type = type;
  11657. if (!this._doNotHandleContextLost) {
  11658. texture._bufferView = data;
  11659. }
  11660. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11661. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11662. // Filters
  11663. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11664. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11665. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11666. if (generateMipMaps) {
  11667. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11668. }
  11669. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11670. this._internalTexturesCache.push(texture);
  11671. return texture;
  11672. };
  11673. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11674. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11675. texture.baseWidth = width;
  11676. texture.baseHeight = height;
  11677. if (generateMipMaps) {
  11678. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11679. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11680. }
  11681. // this.resetTextureCache();
  11682. texture.width = width;
  11683. texture.height = height;
  11684. texture.isReady = false;
  11685. texture.generateMipMaps = generateMipMaps;
  11686. texture.samplingMode = samplingMode;
  11687. this.updateTextureSamplingMode(samplingMode, texture);
  11688. this._internalTexturesCache.push(texture);
  11689. return texture;
  11690. };
  11691. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11692. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11693. if (texture.isCube) {
  11694. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11695. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11696. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11697. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11698. }
  11699. else if (texture.is3D) {
  11700. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11701. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11702. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11703. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11704. }
  11705. else {
  11706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11707. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11709. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11710. }
  11711. texture.samplingMode = samplingMode;
  11712. };
  11713. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11714. if (premulAlpha === void 0) { premulAlpha = false; }
  11715. if (!texture) {
  11716. return;
  11717. }
  11718. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11719. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11720. if (premulAlpha) {
  11721. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11722. }
  11723. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11724. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11725. if (texture.generateMipMaps) {
  11726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11727. }
  11728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11729. if (premulAlpha) {
  11730. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11731. }
  11732. texture.isReady = true;
  11733. };
  11734. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11735. if (!texture || texture._isDisabled) {
  11736. return;
  11737. }
  11738. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11739. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11740. try {
  11741. // Testing video texture support
  11742. if (this._videoTextureSupported === undefined) {
  11743. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11744. if (this._gl.getError() !== 0) {
  11745. this._videoTextureSupported = false;
  11746. }
  11747. else {
  11748. this._videoTextureSupported = true;
  11749. }
  11750. }
  11751. // Copy video through the current working canvas if video texture is not supported
  11752. if (!this._videoTextureSupported) {
  11753. if (!texture._workingCanvas) {
  11754. texture._workingCanvas = document.createElement("canvas");
  11755. var context = texture._workingCanvas.getContext("2d");
  11756. if (!context) {
  11757. throw new Error("Unable to get 2d context");
  11758. }
  11759. texture._workingContext = context;
  11760. texture._workingCanvas.width = texture.width;
  11761. texture._workingCanvas.height = texture.height;
  11762. }
  11763. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11765. }
  11766. else {
  11767. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11768. }
  11769. if (texture.generateMipMaps) {
  11770. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11771. }
  11772. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11773. // this.resetTextureCache();
  11774. texture.isReady = true;
  11775. }
  11776. catch (ex) {
  11777. // Something unexpected
  11778. // Let's disable the texture
  11779. texture._isDisabled = true;
  11780. }
  11781. };
  11782. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11783. var fullOptions = new RenderTargetCreationOptions();
  11784. if (options !== undefined && typeof options === "object") {
  11785. fullOptions.generateMipMaps = options.generateMipMaps;
  11786. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11787. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11788. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11789. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11790. }
  11791. else {
  11792. fullOptions.generateMipMaps = options;
  11793. fullOptions.generateDepthBuffer = true;
  11794. fullOptions.generateStencilBuffer = false;
  11795. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11796. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11797. }
  11798. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11799. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11800. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11801. }
  11802. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11803. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11804. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11805. }
  11806. var gl = this._gl;
  11807. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11808. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11809. var width = size.width || size;
  11810. var height = size.height || size;
  11811. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11812. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11813. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11814. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11815. }
  11816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11820. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11821. // Create the framebuffer
  11822. var framebuffer = gl.createFramebuffer();
  11823. this.bindUnboundFramebuffer(framebuffer);
  11824. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11826. if (fullOptions.generateMipMaps) {
  11827. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11828. }
  11829. // Unbind
  11830. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11831. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11832. this.bindUnboundFramebuffer(null);
  11833. texture._framebuffer = framebuffer;
  11834. texture.baseWidth = width;
  11835. texture.baseHeight = height;
  11836. texture.width = width;
  11837. texture.height = height;
  11838. texture.isReady = true;
  11839. texture.samples = 1;
  11840. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11841. texture.samplingMode = fullOptions.samplingMode;
  11842. texture.type = fullOptions.type;
  11843. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11844. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11845. // this.resetTextureCache();
  11846. this._internalTexturesCache.push(texture);
  11847. return texture;
  11848. };
  11849. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11850. var generateMipMaps = false;
  11851. var generateDepthBuffer = true;
  11852. var generateStencilBuffer = false;
  11853. var generateDepthTexture = false;
  11854. var textureCount = 1;
  11855. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11856. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11857. var types = [], samplingModes = [];
  11858. if (options !== undefined) {
  11859. generateMipMaps = options.generateMipMaps;
  11860. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11861. generateStencilBuffer = options.generateStencilBuffer;
  11862. generateDepthTexture = options.generateDepthTexture;
  11863. textureCount = options.textureCount || 1;
  11864. if (options.types) {
  11865. types = options.types;
  11866. }
  11867. if (options.samplingModes) {
  11868. samplingModes = options.samplingModes;
  11869. }
  11870. }
  11871. var gl = this._gl;
  11872. // Create the framebuffer
  11873. var framebuffer = gl.createFramebuffer();
  11874. this.bindUnboundFramebuffer(framebuffer);
  11875. var width = size.width || size;
  11876. var height = size.height || size;
  11877. var textures = [];
  11878. var attachments = [];
  11879. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11880. for (var i = 0; i < textureCount; i++) {
  11881. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11882. var type = types[i] || defaultType;
  11883. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11884. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11885. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11886. }
  11887. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11888. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11889. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11890. }
  11891. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11892. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11893. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11894. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11895. }
  11896. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11897. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11898. textures.push(texture);
  11899. attachments.push(attachment);
  11900. gl.activeTexture(gl["TEXTURE" + i]);
  11901. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11905. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11906. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11907. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11908. if (generateMipMaps) {
  11909. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11910. }
  11911. // Unbind
  11912. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11913. texture._framebuffer = framebuffer;
  11914. texture._depthStencilBuffer = depthStencilBuffer;
  11915. texture.baseWidth = width;
  11916. texture.baseHeight = height;
  11917. texture.width = width;
  11918. texture.height = height;
  11919. texture.isReady = true;
  11920. texture.samples = 1;
  11921. texture.generateMipMaps = generateMipMaps;
  11922. texture.samplingMode = samplingMode;
  11923. texture.type = type;
  11924. texture._generateDepthBuffer = generateDepthBuffer;
  11925. texture._generateStencilBuffer = generateStencilBuffer;
  11926. texture._attachments = attachments;
  11927. this._internalTexturesCache.push(texture);
  11928. }
  11929. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11930. // Depth texture
  11931. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11932. gl.activeTexture(gl.TEXTURE0);
  11933. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11938. 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);
  11939. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11940. depthTexture._framebuffer = framebuffer;
  11941. depthTexture.baseWidth = width;
  11942. depthTexture.baseHeight = height;
  11943. depthTexture.width = width;
  11944. depthTexture.height = height;
  11945. depthTexture.isReady = true;
  11946. depthTexture.samples = 1;
  11947. depthTexture.generateMipMaps = generateMipMaps;
  11948. depthTexture.samplingMode = gl.NEAREST;
  11949. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11950. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11951. textures.push(depthTexture);
  11952. this._internalTexturesCache.push(depthTexture);
  11953. }
  11954. gl.drawBuffers(attachments);
  11955. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11956. this.bindUnboundFramebuffer(null);
  11957. this.resetTextureCache();
  11958. return textures;
  11959. };
  11960. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11961. if (samples === void 0) { samples = 1; }
  11962. var depthStencilBuffer = null;
  11963. var gl = this._gl;
  11964. // Create the depth/stencil buffer
  11965. if (generateStencilBuffer) {
  11966. depthStencilBuffer = gl.createRenderbuffer();
  11967. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11968. if (samples > 1) {
  11969. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11970. }
  11971. else {
  11972. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11973. }
  11974. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11975. }
  11976. else if (generateDepthBuffer) {
  11977. depthStencilBuffer = gl.createRenderbuffer();
  11978. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11979. if (samples > 1) {
  11980. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11981. }
  11982. else {
  11983. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11984. }
  11985. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11986. }
  11987. return depthStencilBuffer;
  11988. };
  11989. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11990. if (this.webGLVersion < 2 || !texture) {
  11991. return 1;
  11992. }
  11993. if (texture.samples === samples) {
  11994. return samples;
  11995. }
  11996. var gl = this._gl;
  11997. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11998. // Dispose previous render buffers
  11999. if (texture._depthStencilBuffer) {
  12000. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12001. texture._depthStencilBuffer = null;
  12002. }
  12003. if (texture._MSAAFramebuffer) {
  12004. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12005. texture._MSAAFramebuffer = null;
  12006. }
  12007. if (texture._MSAARenderBuffer) {
  12008. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12009. texture._MSAARenderBuffer = null;
  12010. }
  12011. if (samples > 1) {
  12012. var framebuffer = gl.createFramebuffer();
  12013. if (!framebuffer) {
  12014. throw new Error("Unable to create multi sampled framebuffer");
  12015. }
  12016. texture._MSAAFramebuffer = framebuffer;
  12017. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12018. var colorRenderbuffer = gl.createRenderbuffer();
  12019. if (!colorRenderbuffer) {
  12020. throw new Error("Unable to create multi sampled framebuffer");
  12021. }
  12022. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12023. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12024. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12025. texture._MSAARenderBuffer = colorRenderbuffer;
  12026. }
  12027. else {
  12028. this.bindUnboundFramebuffer(texture._framebuffer);
  12029. }
  12030. texture.samples = samples;
  12031. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12032. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12033. this.bindUnboundFramebuffer(null);
  12034. return samples;
  12035. };
  12036. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12037. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12038. return 1;
  12039. }
  12040. if (textures[0].samples === samples) {
  12041. return samples;
  12042. }
  12043. var gl = this._gl;
  12044. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12045. // Dispose previous render buffers
  12046. if (textures[0]._depthStencilBuffer) {
  12047. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12048. textures[0]._depthStencilBuffer = null;
  12049. }
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12052. textures[0]._MSAAFramebuffer = null;
  12053. }
  12054. for (var i = 0; i < textures.length; i++) {
  12055. if (textures[i]._MSAARenderBuffer) {
  12056. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12057. textures[i]._MSAARenderBuffer = null;
  12058. }
  12059. }
  12060. if (samples > 1) {
  12061. var framebuffer = gl.createFramebuffer();
  12062. if (!framebuffer) {
  12063. throw new Error("Unable to create multi sampled framebuffer");
  12064. }
  12065. this.bindUnboundFramebuffer(framebuffer);
  12066. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12067. var attachments = [];
  12068. for (var i = 0; i < textures.length; i++) {
  12069. var texture = textures[i];
  12070. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. var colorRenderbuffer = gl.createRenderbuffer();
  12072. if (!colorRenderbuffer) {
  12073. throw new Error("Unable to create multi sampled framebuffer");
  12074. }
  12075. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12076. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12077. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12078. texture._MSAAFramebuffer = framebuffer;
  12079. texture._MSAARenderBuffer = colorRenderbuffer;
  12080. texture.samples = samples;
  12081. texture._depthStencilBuffer = depthStencilBuffer;
  12082. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12083. attachments.push(attachment);
  12084. }
  12085. gl.drawBuffers(attachments);
  12086. }
  12087. else {
  12088. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12089. }
  12090. this.bindUnboundFramebuffer(null);
  12091. return samples;
  12092. };
  12093. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12094. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12095. };
  12096. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12097. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12098. };
  12099. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12100. var gl = this._gl;
  12101. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12102. var generateMipMaps = true;
  12103. var generateDepthBuffer = true;
  12104. var generateStencilBuffer = false;
  12105. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12106. if (options !== undefined) {
  12107. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12108. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12109. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12110. if (options.samplingMode !== undefined) {
  12111. samplingMode = options.samplingMode;
  12112. }
  12113. }
  12114. texture.isCube = true;
  12115. texture.generateMipMaps = generateMipMaps;
  12116. texture.samples = 1;
  12117. texture.samplingMode = samplingMode;
  12118. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12119. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12120. for (var face = 0; face < 6; face++) {
  12121. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12122. }
  12123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12127. // Create the framebuffer
  12128. var framebuffer = gl.createFramebuffer();
  12129. this.bindUnboundFramebuffer(framebuffer);
  12130. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12131. // Mipmaps
  12132. if (texture.generateMipMaps) {
  12133. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12134. }
  12135. // Unbind
  12136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12137. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12138. this.bindUnboundFramebuffer(null);
  12139. texture._framebuffer = framebuffer;
  12140. texture.width = size;
  12141. texture.height = size;
  12142. texture.isReady = true;
  12143. //this.resetTextureCache();
  12144. this._internalTexturesCache.push(texture);
  12145. return texture;
  12146. };
  12147. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12148. var _this = this;
  12149. if (onLoad === void 0) { onLoad = null; }
  12150. if (onError === void 0) { onError = null; }
  12151. if (forcedExtension === void 0) { forcedExtension = null; }
  12152. var callback = function (loadData) {
  12153. if (!loadData) {
  12154. if (onLoad) {
  12155. onLoad(null);
  12156. }
  12157. return;
  12158. }
  12159. var texture = loadData.texture;
  12160. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12161. texture._lodGenerationScale = scale;
  12162. texture._lodGenerationOffset = offset;
  12163. if (_this._caps.textureLOD) {
  12164. // Do not add extra process if texture lod is supported.
  12165. if (onLoad) {
  12166. onLoad(texture);
  12167. }
  12168. return;
  12169. }
  12170. var mipSlices = 3;
  12171. var gl = _this._gl;
  12172. var width = loadData.width;
  12173. if (!width) {
  12174. return;
  12175. }
  12176. var textures = [];
  12177. for (var i = 0; i < mipSlices; i++) {
  12178. //compute LOD from even spacing in smoothness (matching shader calculation)
  12179. var smoothness = i / (mipSlices - 1);
  12180. var roughness = 1 - smoothness;
  12181. var minLODIndex = offset; // roughness = 0
  12182. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12183. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12184. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12185. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12186. glTextureFromLod.isCube = true;
  12187. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12188. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12192. if (loadData.isDDS) {
  12193. var info = loadData.info;
  12194. var data = loadData.data;
  12195. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12196. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12197. }
  12198. else {
  12199. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12200. }
  12201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12202. // Wrap in a base texture for easy binding.
  12203. var lodTexture = new BABYLON.BaseTexture(scene);
  12204. lodTexture.isCube = true;
  12205. lodTexture._texture = glTextureFromLod;
  12206. glTextureFromLod.isReady = true;
  12207. textures.push(lodTexture);
  12208. }
  12209. texture._lodTextureHigh = textures[2];
  12210. texture._lodTextureMid = textures[1];
  12211. texture._lodTextureLow = textures[0];
  12212. if (onLoad) {
  12213. onLoad(texture);
  12214. }
  12215. };
  12216. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12217. };
  12218. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12219. var _this = this;
  12220. if (onLoad === void 0) { onLoad = null; }
  12221. if (onError === void 0) { onError = null; }
  12222. if (forcedExtension === void 0) { forcedExtension = null; }
  12223. var gl = this._gl;
  12224. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12225. texture.isCube = true;
  12226. texture.url = rootUrl;
  12227. texture.generateMipMaps = !noMipmap;
  12228. if (!this._doNotHandleContextLost) {
  12229. texture._extension = forcedExtension;
  12230. texture._files = files;
  12231. }
  12232. var isKTX = false;
  12233. var isDDS = false;
  12234. var lastDot = rootUrl.lastIndexOf('.');
  12235. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12236. if (this._textureFormatInUse) {
  12237. extension = this._textureFormatInUse;
  12238. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12239. isKTX = true;
  12240. }
  12241. else {
  12242. isDDS = (extension === ".dds");
  12243. }
  12244. var onerror = function (request, exception) {
  12245. if (onError && request) {
  12246. onError(request.status + " " + request.statusText, exception);
  12247. }
  12248. };
  12249. if (isKTX) {
  12250. this._loadFile(rootUrl, function (data) {
  12251. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12252. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12253. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12254. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12255. ktx.uploadLevels(_this._gl, !noMipmap);
  12256. _this.setCubeMapTextureParams(gl, loadMipmap);
  12257. texture.width = ktx.pixelWidth;
  12258. texture.height = ktx.pixelHeight;
  12259. texture.isReady = true;
  12260. }, undefined, undefined, true, onerror);
  12261. }
  12262. else if (isDDS) {
  12263. if (files && files.length === 6) {
  12264. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12265. var info;
  12266. var loadMipmap = false;
  12267. var width = 0;
  12268. for (var index = 0; index < imgs.length; index++) {
  12269. var data = imgs[index];
  12270. info = BABYLON.DDSTools.GetDDSInfo(data);
  12271. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12272. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12273. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12274. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12275. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12276. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12277. }
  12278. texture.width = info.width;
  12279. texture.height = info.height;
  12280. texture.type = info.textureType;
  12281. width = info.width;
  12282. }
  12283. _this.setCubeMapTextureParams(gl, loadMipmap);
  12284. texture.isReady = true;
  12285. if (onLoad) {
  12286. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12287. }
  12288. }, files, onError);
  12289. }
  12290. else {
  12291. this._loadFile(rootUrl, function (data) {
  12292. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12293. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12294. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12295. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12296. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12297. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12298. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12299. }
  12300. _this.setCubeMapTextureParams(gl, loadMipmap);
  12301. texture.width = info.width;
  12302. texture.height = info.height;
  12303. texture.isReady = true;
  12304. texture.type = info.textureType;
  12305. if (onLoad) {
  12306. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12307. }
  12308. }, undefined, undefined, true, onerror);
  12309. }
  12310. }
  12311. else {
  12312. if (!files) {
  12313. throw new Error("Cannot load cubemap because files were not defined");
  12314. }
  12315. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12316. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12317. var height = width;
  12318. _this._prepareWorkingCanvas();
  12319. if (!_this._workingCanvas || !_this._workingContext) {
  12320. return;
  12321. }
  12322. _this._workingCanvas.width = width;
  12323. _this._workingCanvas.height = height;
  12324. var faces = [
  12325. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12326. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12327. ];
  12328. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12329. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12330. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12331. for (var index = 0; index < faces.length; index++) {
  12332. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12333. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12334. }
  12335. if (!noMipmap) {
  12336. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12337. }
  12338. _this.setCubeMapTextureParams(gl, !noMipmap);
  12339. texture.width = width;
  12340. texture.height = height;
  12341. texture.isReady = true;
  12342. if (format) {
  12343. texture.format = format;
  12344. }
  12345. texture.onLoadedObservable.notifyObservers(texture);
  12346. texture.onLoadedObservable.clear();
  12347. if (onLoad) {
  12348. onLoad();
  12349. }
  12350. }, files, onError);
  12351. }
  12352. this._internalTexturesCache.push(texture);
  12353. return texture;
  12354. };
  12355. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12360. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12361. // this.resetTextureCache();
  12362. };
  12363. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12364. if (compression === void 0) { compression = null; }
  12365. if (level === void 0) { level = 0; }
  12366. texture._bufferViewArray = data;
  12367. texture.format = format;
  12368. texture.type = type;
  12369. texture.invertY = invertY;
  12370. texture._compression = compression;
  12371. var gl = this._gl;
  12372. var textureType = this._getWebGLTextureType(type);
  12373. var internalFormat = this._getInternalFormat(format);
  12374. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12375. var needConversion = false;
  12376. if (internalFormat === gl.RGB) {
  12377. internalFormat = gl.RGBA;
  12378. needConversion = true;
  12379. }
  12380. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12381. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12382. if (texture.width % 4 !== 0) {
  12383. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12384. }
  12385. // Data are known to be in +X +Y +Z -X -Y -Z
  12386. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12387. var faceData = data[faceIndex];
  12388. if (compression) {
  12389. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12390. }
  12391. else {
  12392. if (needConversion) {
  12393. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12394. }
  12395. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12396. }
  12397. }
  12398. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12399. if (isPot && texture.generateMipMaps && level === 0) {
  12400. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12401. }
  12402. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12403. // this.resetTextureCache();
  12404. texture.isReady = true;
  12405. };
  12406. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12407. if (compression === void 0) { compression = null; }
  12408. var gl = this._gl;
  12409. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12410. texture.isCube = true;
  12411. texture.generateMipMaps = generateMipMaps;
  12412. texture.format = format;
  12413. texture.type = type;
  12414. if (!this._doNotHandleContextLost) {
  12415. texture._bufferViewArray = data;
  12416. }
  12417. var textureType = this._getWebGLTextureType(type);
  12418. var internalFormat = this._getInternalFormat(format);
  12419. if (internalFormat === gl.RGB) {
  12420. internalFormat = gl.RGBA;
  12421. }
  12422. var width = size;
  12423. var height = width;
  12424. texture.width = width;
  12425. texture.height = height;
  12426. // Double check on POT to generate Mips.
  12427. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12428. if (!isPot) {
  12429. generateMipMaps = false;
  12430. }
  12431. // Upload data if needed. The texture won't be ready until then.
  12432. if (data) {
  12433. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12434. }
  12435. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12436. // Filters
  12437. if (data && generateMipMaps) {
  12438. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12439. }
  12440. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12443. }
  12444. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12447. }
  12448. else {
  12449. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12452. }
  12453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12456. return texture;
  12457. };
  12458. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12459. var _this = this;
  12460. if (onLoad === void 0) { onLoad = null; }
  12461. if (onError === void 0) { onError = null; }
  12462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12463. if (invertY === void 0) { invertY = false; }
  12464. var gl = this._gl;
  12465. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12466. scene._addPendingData(texture);
  12467. texture.url = url;
  12468. this._internalTexturesCache.push(texture);
  12469. var onerror = function (request, exception) {
  12470. scene._removePendingData(texture);
  12471. if (onError && request) {
  12472. onError(request.status + " " + request.statusText, exception);
  12473. }
  12474. };
  12475. var internalCallback = function (data) {
  12476. var width = texture.width;
  12477. var faceDataArrays = callback(data);
  12478. if (!faceDataArrays) {
  12479. return;
  12480. }
  12481. if (mipmmapGenerator) {
  12482. var textureType = _this._getWebGLTextureType(type);
  12483. var internalFormat = _this._getInternalFormat(format);
  12484. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12485. var needConversion = false;
  12486. if (internalFormat === gl.RGB) {
  12487. internalFormat = gl.RGBA;
  12488. needConversion = true;
  12489. }
  12490. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12491. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12492. var mipData = mipmmapGenerator(faceDataArrays);
  12493. for (var level = 0; level < mipData.length; level++) {
  12494. var mipSize = width >> level;
  12495. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12496. var mipFaceData = mipData[level][faceIndex];
  12497. if (needConversion) {
  12498. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12499. }
  12500. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12501. }
  12502. }
  12503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12504. }
  12505. else {
  12506. texture.generateMipMaps = !noMipmap;
  12507. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12508. }
  12509. texture.isReady = true;
  12510. // this.resetTextureCache();
  12511. scene._removePendingData(texture);
  12512. if (onLoad) {
  12513. onLoad();
  12514. }
  12515. };
  12516. this._loadFile(url, function (data) {
  12517. internalCallback(data);
  12518. }, undefined, scene.database, true, onerror);
  12519. return texture;
  12520. };
  12521. ;
  12522. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12523. if (compression === void 0) { compression = null; }
  12524. var internalFormat = this._getInternalFormat(format);
  12525. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12526. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12527. if (!this._doNotHandleContextLost) {
  12528. texture._bufferView = data;
  12529. texture.format = format;
  12530. texture.invertY = invertY;
  12531. texture._compression = compression;
  12532. }
  12533. if (texture.width % 4 !== 0) {
  12534. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12535. }
  12536. if (compression && data) {
  12537. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12538. }
  12539. else {
  12540. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12541. }
  12542. if (texture.generateMipMaps) {
  12543. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12544. }
  12545. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12546. // this.resetTextureCache();
  12547. texture.isReady = true;
  12548. };
  12549. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12550. if (compression === void 0) { compression = null; }
  12551. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12552. texture.baseWidth = width;
  12553. texture.baseHeight = height;
  12554. texture.baseDepth = depth;
  12555. texture.width = width;
  12556. texture.height = height;
  12557. texture.depth = depth;
  12558. texture.format = format;
  12559. texture.generateMipMaps = generateMipMaps;
  12560. texture.samplingMode = samplingMode;
  12561. texture.is3D = true;
  12562. if (!this._doNotHandleContextLost) {
  12563. texture._bufferView = data;
  12564. }
  12565. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12566. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12567. // Filters
  12568. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12569. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12570. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12571. if (generateMipMaps) {
  12572. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12573. }
  12574. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12575. this._internalTexturesCache.push(texture);
  12576. return texture;
  12577. };
  12578. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12579. var gl = this._gl;
  12580. if (!gl) {
  12581. return;
  12582. }
  12583. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12586. if (!noMipmap && !isCompressed) {
  12587. gl.generateMipmap(gl.TEXTURE_2D);
  12588. }
  12589. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12590. // this.resetTextureCache();
  12591. if (scene) {
  12592. scene._removePendingData(texture);
  12593. }
  12594. texture.onLoadedObservable.notifyObservers(texture);
  12595. texture.onLoadedObservable.clear();
  12596. };
  12597. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12598. var _this = this;
  12599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12600. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12601. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12602. var gl = this._gl;
  12603. if (!gl) {
  12604. return;
  12605. }
  12606. if (!texture._webGLTexture) {
  12607. // this.resetTextureCache();
  12608. if (scene) {
  12609. scene._removePendingData(texture);
  12610. }
  12611. return;
  12612. }
  12613. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12614. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12615. texture.baseWidth = width;
  12616. texture.baseHeight = height;
  12617. texture.width = potWidth;
  12618. texture.height = potHeight;
  12619. texture.isReady = true;
  12620. if (processFunction(potWidth, potHeight, function () {
  12621. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12622. })) {
  12623. // Returning as texture needs extra async steps
  12624. return;
  12625. }
  12626. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12627. };
  12628. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12629. // Create new RGBA data container.
  12630. var rgbaData;
  12631. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12632. rgbaData = new Float32Array(width * height * 4);
  12633. }
  12634. else {
  12635. rgbaData = new Uint32Array(width * height * 4);
  12636. }
  12637. // Convert each pixel.
  12638. for (var x = 0; x < width; x++) {
  12639. for (var y = 0; y < height; y++) {
  12640. var index = (y * width + x) * 3;
  12641. var newIndex = (y * width + x) * 4;
  12642. // Map Old Value to new value.
  12643. rgbaData[newIndex + 0] = rgbData[index + 0];
  12644. rgbaData[newIndex + 1] = rgbData[index + 1];
  12645. rgbaData[newIndex + 2] = rgbData[index + 2];
  12646. // Add fully opaque alpha channel.
  12647. rgbaData[newIndex + 3] = 1;
  12648. }
  12649. }
  12650. return rgbaData;
  12651. };
  12652. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12653. var gl = this._gl;
  12654. if (texture._framebuffer) {
  12655. gl.deleteFramebuffer(texture._framebuffer);
  12656. texture._framebuffer = null;
  12657. }
  12658. if (texture._depthStencilBuffer) {
  12659. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12660. texture._depthStencilBuffer = null;
  12661. }
  12662. if (texture._MSAAFramebuffer) {
  12663. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12664. texture._MSAAFramebuffer = null;
  12665. }
  12666. if (texture._MSAARenderBuffer) {
  12667. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12668. texture._MSAARenderBuffer = null;
  12669. }
  12670. };
  12671. Engine.prototype._releaseTexture = function (texture) {
  12672. var gl = this._gl;
  12673. this._releaseFramebufferObjects(texture);
  12674. gl.deleteTexture(texture._webGLTexture);
  12675. // Unbind channels
  12676. this.unbindAllTextures();
  12677. var index = this._internalTexturesCache.indexOf(texture);
  12678. if (index !== -1) {
  12679. this._internalTexturesCache.splice(index, 1);
  12680. }
  12681. // Integrated fixed lod samplers.
  12682. if (texture._lodTextureHigh) {
  12683. texture._lodTextureHigh.dispose();
  12684. }
  12685. if (texture._lodTextureMid) {
  12686. texture._lodTextureMid.dispose();
  12687. }
  12688. if (texture._lodTextureLow) {
  12689. texture._lodTextureLow.dispose();
  12690. }
  12691. };
  12692. Engine.prototype.setProgram = function (program) {
  12693. if (this._currentProgram !== program) {
  12694. this._gl.useProgram(program);
  12695. this._currentProgram = program;
  12696. }
  12697. };
  12698. Engine.prototype.bindSamplers = function (effect) {
  12699. this.setProgram(effect.getProgram());
  12700. var samplers = effect.getSamplers();
  12701. for (var index = 0; index < samplers.length; index++) {
  12702. var uniform = effect.getUniform(samplers[index]);
  12703. if (uniform) {
  12704. this._boundUniforms[index] = uniform;
  12705. }
  12706. }
  12707. this._currentEffect = null;
  12708. };
  12709. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12710. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12711. return;
  12712. }
  12713. // Remove
  12714. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12715. // Bind last to it
  12716. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12717. // Bind to dummy
  12718. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12719. };
  12720. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12721. if (!internalTexture) {
  12722. return -1;
  12723. }
  12724. internalTexture._initialSlot = channel;
  12725. if (this.disableTextureBindingOptimization) {
  12726. if (channel !== internalTexture._designatedSlot) {
  12727. this._textureCollisions.addCount(1, false);
  12728. }
  12729. }
  12730. else {
  12731. if (channel !== internalTexture._designatedSlot) {
  12732. if (internalTexture._designatedSlot > -1) {
  12733. return internalTexture._designatedSlot;
  12734. }
  12735. else {
  12736. // No slot for this texture, let's pick a new one (if we find a free slot)
  12737. if (this._nextFreeTextureSlots.length) {
  12738. return this._nextFreeTextureSlots[0];
  12739. }
  12740. // We need to recycle the oldest bound texture, sorry.
  12741. this._textureCollisions.addCount(1, false);
  12742. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12743. }
  12744. }
  12745. }
  12746. return channel;
  12747. };
  12748. Engine.prototype._linkTrackers = function (previous, next) {
  12749. previous.next = next;
  12750. next.previous = previous;
  12751. };
  12752. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12753. var currentSlot = internalTexture._designatedSlot;
  12754. if (currentSlot === -1) {
  12755. return -1;
  12756. }
  12757. internalTexture._designatedSlot = -1;
  12758. // Remove from bound list
  12759. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12760. // Free the slot
  12761. this._boundTexturesCache[currentSlot] = null;
  12762. this._nextFreeTextureSlots.push(currentSlot);
  12763. return currentSlot;
  12764. };
  12765. Engine.prototype._activateCurrentTexture = function () {
  12766. if (this._currentTextureChannel !== this._activeChannel) {
  12767. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12768. this._currentTextureChannel = this._activeChannel;
  12769. }
  12770. };
  12771. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12772. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12773. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12774. this._activeChannel = texture._designatedSlot;
  12775. }
  12776. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12777. var isTextureForRendering = texture && texture._initialSlot > -1;
  12778. if (currentTextureBound !== texture) {
  12779. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12780. this._removeDesignatedSlot(currentTextureBound);
  12781. }
  12782. this._activateCurrentTexture();
  12783. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12784. this._boundTexturesCache[this._activeChannel] = texture;
  12785. if (texture) {
  12786. if (!this.disableTextureBindingOptimization) {
  12787. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12788. if (slotIndex > -1) {
  12789. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12790. }
  12791. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  12792. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  12793. }
  12794. texture._designatedSlot = this._activeChannel;
  12795. }
  12796. }
  12797. else if (forTextureDataUpdate) {
  12798. this._activateCurrentTexture();
  12799. }
  12800. if (isTextureForRendering && !forTextureDataUpdate) {
  12801. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12802. }
  12803. };
  12804. Engine.prototype._bindTexture = function (channel, texture) {
  12805. if (channel < 0) {
  12806. return;
  12807. }
  12808. if (texture) {
  12809. channel = this._getCorrectTextureChannel(channel, texture);
  12810. }
  12811. this._activeChannel = channel;
  12812. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12813. };
  12814. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12815. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12816. };
  12817. Engine.prototype.unbindAllTextures = function () {
  12818. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12819. this._activeChannel = channel;
  12820. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12821. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12822. if (this.webGLVersion > 1) {
  12823. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12824. }
  12825. }
  12826. };
  12827. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12828. if (channel < 0) {
  12829. return;
  12830. }
  12831. if (uniform) {
  12832. this._boundUniforms[channel] = uniform;
  12833. }
  12834. this._setTexture(channel, texture);
  12835. };
  12836. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12837. var uniform = this._boundUniforms[sourceSlot];
  12838. if (uniform._currentState === destination) {
  12839. return;
  12840. }
  12841. this._gl.uniform1i(uniform, destination);
  12842. uniform._currentState = destination;
  12843. };
  12844. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12845. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12846. // Not ready?
  12847. if (!texture) {
  12848. if (this._boundTexturesCache[channel] != null) {
  12849. this._activeChannel = channel;
  12850. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12852. if (this.webGLVersion > 1) {
  12853. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12854. }
  12855. }
  12856. return false;
  12857. }
  12858. // Video
  12859. if (texture.video) {
  12860. this._activeChannel = channel;
  12861. texture.update();
  12862. }
  12863. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12864. texture.delayLoad();
  12865. return false;
  12866. }
  12867. var internalTexture;
  12868. if (texture.isReady()) {
  12869. internalTexture = texture.getInternalTexture();
  12870. }
  12871. else if (texture.isCube) {
  12872. internalTexture = this.emptyCubeTexture;
  12873. }
  12874. else if (texture.is3D) {
  12875. internalTexture = this.emptyTexture3D;
  12876. }
  12877. else {
  12878. internalTexture = this.emptyTexture;
  12879. }
  12880. if (!isPartOfTextureArray) {
  12881. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12882. }
  12883. if (this._boundTexturesCache[channel] === internalTexture) {
  12884. this._moveBoundTextureOnTop(internalTexture);
  12885. if (!isPartOfTextureArray) {
  12886. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12887. }
  12888. return false;
  12889. }
  12890. this._activeChannel = channel;
  12891. if (internalTexture && internalTexture.is3D) {
  12892. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12893. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12894. internalTexture._cachedWrapU = texture.wrapU;
  12895. switch (texture.wrapU) {
  12896. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12897. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12898. break;
  12899. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12900. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12901. break;
  12902. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12903. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12904. break;
  12905. }
  12906. }
  12907. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12908. internalTexture._cachedWrapV = texture.wrapV;
  12909. switch (texture.wrapV) {
  12910. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12911. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12912. break;
  12913. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12914. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12915. break;
  12916. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12917. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12918. break;
  12919. }
  12920. }
  12921. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12922. internalTexture._cachedWrapR = texture.wrapR;
  12923. switch (texture.wrapV) {
  12924. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12925. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12926. break;
  12927. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12928. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12929. break;
  12930. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12931. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12932. break;
  12933. }
  12934. }
  12935. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12936. }
  12937. else if (internalTexture && internalTexture.isCube) {
  12938. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12939. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12940. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12941. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12942. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12943. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12944. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12945. }
  12946. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12947. }
  12948. else {
  12949. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12950. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12951. internalTexture._cachedWrapU = texture.wrapU;
  12952. switch (texture.wrapU) {
  12953. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12954. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12955. break;
  12956. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12957. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12958. break;
  12959. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12960. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12961. break;
  12962. }
  12963. }
  12964. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12965. internalTexture._cachedWrapV = texture.wrapV;
  12966. switch (texture.wrapV) {
  12967. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12968. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12969. break;
  12970. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12971. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12972. break;
  12973. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12974. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12975. break;
  12976. }
  12977. }
  12978. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12979. }
  12980. return true;
  12981. };
  12982. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12983. if (channel < 0 || !uniform) {
  12984. return;
  12985. }
  12986. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12987. this._textureUnits = new Int32Array(textures.length);
  12988. }
  12989. for (var i = 0; i < textures.length; i++) {
  12990. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12991. }
  12992. this._gl.uniform1iv(uniform, this._textureUnits);
  12993. for (var index = 0; index < textures.length; index++) {
  12994. this._setTexture(this._textureUnits[index], textures[index], true);
  12995. }
  12996. };
  12997. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12998. var internalTexture = texture.getInternalTexture();
  12999. if (!internalTexture) {
  13000. return;
  13001. }
  13002. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13003. var value = texture.anisotropicFilteringLevel;
  13004. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13005. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13006. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13007. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13008. }
  13009. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13010. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13011. internalTexture._cachedAnisotropicFilteringLevel = value;
  13012. }
  13013. };
  13014. Engine.prototype.readPixels = function (x, y, width, height) {
  13015. var data = new Uint8Array(height * width * 4);
  13016. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13017. return data;
  13018. };
  13019. /**
  13020. * Add an externaly attached data from its key.
  13021. * This method call will fail and return false, if such key already exists.
  13022. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13023. * @param key the unique key that identifies the data
  13024. * @param data the data object to associate to the key for this Engine instance
  13025. * @return true if no such key were already present and the data was added successfully, false otherwise
  13026. */
  13027. Engine.prototype.addExternalData = function (key, data) {
  13028. if (!this._externalData) {
  13029. this._externalData = new BABYLON.StringDictionary();
  13030. }
  13031. return this._externalData.add(key, data);
  13032. };
  13033. /**
  13034. * Get an externaly attached data from its key
  13035. * @param key the unique key that identifies the data
  13036. * @return the associated data, if present (can be null), or undefined if not present
  13037. */
  13038. Engine.prototype.getExternalData = function (key) {
  13039. if (!this._externalData) {
  13040. this._externalData = new BABYLON.StringDictionary();
  13041. }
  13042. return this._externalData.get(key);
  13043. };
  13044. /**
  13045. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13046. * @param key the unique key that identifies the data
  13047. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13048. * @return the associated data, can be null if the factory returned null.
  13049. */
  13050. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13051. if (!this._externalData) {
  13052. this._externalData = new BABYLON.StringDictionary();
  13053. }
  13054. return this._externalData.getOrAddWithFactory(key, factory);
  13055. };
  13056. /**
  13057. * Remove an externaly attached data from the Engine instance
  13058. * @param key the unique key that identifies the data
  13059. * @return true if the data was successfully removed, false if it doesn't exist
  13060. */
  13061. Engine.prototype.removeExternalData = function (key) {
  13062. if (!this._externalData) {
  13063. this._externalData = new BABYLON.StringDictionary();
  13064. }
  13065. return this._externalData.remove(key);
  13066. };
  13067. Engine.prototype.unbindAllAttributes = function () {
  13068. if (this._mustWipeVertexAttributes) {
  13069. this._mustWipeVertexAttributes = false;
  13070. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13071. this._gl.disableVertexAttribArray(i);
  13072. this._vertexAttribArraysEnabled[i] = false;
  13073. this._currentBufferPointers[i].active = false;
  13074. }
  13075. return;
  13076. }
  13077. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13078. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13079. continue;
  13080. }
  13081. this._gl.disableVertexAttribArray(i);
  13082. this._vertexAttribArraysEnabled[i] = false;
  13083. this._currentBufferPointers[i].active = false;
  13084. }
  13085. };
  13086. Engine.prototype.releaseEffects = function () {
  13087. for (var name in this._compiledEffects) {
  13088. this._deleteProgram(this._compiledEffects[name]._program);
  13089. }
  13090. this._compiledEffects = {};
  13091. };
  13092. // Dispose
  13093. Engine.prototype.dispose = function () {
  13094. this.hideLoadingUI();
  13095. this.stopRenderLoop();
  13096. // Release postProcesses
  13097. while (this.postProcesses.length) {
  13098. this.postProcesses[0].dispose();
  13099. }
  13100. // Empty texture
  13101. if (this._emptyTexture) {
  13102. this._releaseTexture(this._emptyTexture);
  13103. this._emptyTexture = null;
  13104. }
  13105. if (this._emptyCubeTexture) {
  13106. this._releaseTexture(this._emptyCubeTexture);
  13107. this._emptyCubeTexture = null;
  13108. }
  13109. // Rescale PP
  13110. if (this._rescalePostProcess) {
  13111. this._rescalePostProcess.dispose();
  13112. }
  13113. // Release scenes
  13114. while (this.scenes.length) {
  13115. this.scenes[0].dispose();
  13116. }
  13117. // Release audio engine
  13118. if (Engine.audioEngine) {
  13119. Engine.audioEngine.dispose();
  13120. }
  13121. // Release effects
  13122. this.releaseEffects();
  13123. // Unbind
  13124. this.unbindAllAttributes();
  13125. if (this._dummyFramebuffer) {
  13126. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13127. }
  13128. //WebVR
  13129. this.disableVR();
  13130. // Events
  13131. if (BABYLON.Tools.IsWindowObjectExist()) {
  13132. window.removeEventListener("blur", this._onBlur);
  13133. window.removeEventListener("focus", this._onFocus);
  13134. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13135. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13136. if (this._renderingCanvas) {
  13137. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13138. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13139. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13140. if (!this._doNotHandleContextLost) {
  13141. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13142. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13143. }
  13144. }
  13145. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13146. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13147. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13148. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13149. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13150. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13151. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13152. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13153. if (this._onVrDisplayConnect) {
  13154. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13155. if (this._onVrDisplayDisconnect) {
  13156. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13157. }
  13158. if (this._onVrDisplayPresentChange) {
  13159. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13160. }
  13161. this._onVrDisplayConnect = null;
  13162. this._onVrDisplayDisconnect = null;
  13163. }
  13164. }
  13165. // Remove from Instances
  13166. var index = Engine.Instances.indexOf(this);
  13167. if (index >= 0) {
  13168. Engine.Instances.splice(index, 1);
  13169. }
  13170. this._workingCanvas = null;
  13171. this._workingContext = null;
  13172. this._currentBufferPointers = [];
  13173. this._renderingCanvas = null;
  13174. this._currentProgram = null;
  13175. this.onResizeObservable.clear();
  13176. this.onCanvasBlurObservable.clear();
  13177. this.onCanvasFocusObservable.clear();
  13178. this.onCanvasPointerOutObservable.clear();
  13179. this.onBeginFrameObservable.clear();
  13180. this.onEndFrameObservable.clear();
  13181. BABYLON.Effect.ResetCache();
  13182. // Abort active requests
  13183. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13184. var request = _a[_i];
  13185. request.abort();
  13186. }
  13187. };
  13188. // Loading screen
  13189. Engine.prototype.displayLoadingUI = function () {
  13190. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13191. return;
  13192. }
  13193. var loadingScreen = this.loadingScreen;
  13194. if (loadingScreen) {
  13195. loadingScreen.displayLoadingUI();
  13196. }
  13197. };
  13198. Engine.prototype.hideLoadingUI = function () {
  13199. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13200. return;
  13201. }
  13202. var loadingScreen = this.loadingScreen;
  13203. if (loadingScreen) {
  13204. loadingScreen.hideLoadingUI();
  13205. }
  13206. };
  13207. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13208. get: function () {
  13209. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13210. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13211. return this._loadingScreen;
  13212. },
  13213. set: function (loadingScreen) {
  13214. this._loadingScreen = loadingScreen;
  13215. },
  13216. enumerable: true,
  13217. configurable: true
  13218. });
  13219. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13220. set: function (text) {
  13221. this.loadingScreen.loadingUIText = text;
  13222. },
  13223. enumerable: true,
  13224. configurable: true
  13225. });
  13226. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13227. set: function (color) {
  13228. this.loadingScreen.loadingUIBackgroundColor = color;
  13229. },
  13230. enumerable: true,
  13231. configurable: true
  13232. });
  13233. Engine.prototype.attachContextLostEvent = function (callback) {
  13234. if (this._renderingCanvas) {
  13235. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13236. }
  13237. };
  13238. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13239. if (this._renderingCanvas) {
  13240. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13241. }
  13242. };
  13243. Engine.prototype.getVertexShaderSource = function (program) {
  13244. var shaders = this._gl.getAttachedShaders(program);
  13245. if (!shaders) {
  13246. return null;
  13247. }
  13248. return this._gl.getShaderSource(shaders[0]);
  13249. };
  13250. Engine.prototype.getFragmentShaderSource = function (program) {
  13251. var shaders = this._gl.getAttachedShaders(program);
  13252. if (!shaders) {
  13253. return null;
  13254. }
  13255. return this._gl.getShaderSource(shaders[1]);
  13256. };
  13257. Engine.prototype.getError = function () {
  13258. return this._gl.getError();
  13259. };
  13260. // FPS
  13261. Engine.prototype.getFps = function () {
  13262. return this._fps;
  13263. };
  13264. Engine.prototype.getDeltaTime = function () {
  13265. return this._deltaTime;
  13266. };
  13267. Engine.prototype._measureFps = function () {
  13268. this._performanceMonitor.sampleFrame();
  13269. this._fps = this._performanceMonitor.averageFPS;
  13270. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13271. };
  13272. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13273. if (faceIndex === void 0) { faceIndex = -1; }
  13274. var gl = this._gl;
  13275. if (!this._dummyFramebuffer) {
  13276. var dummy = gl.createFramebuffer();
  13277. if (!dummy) {
  13278. throw new Error("Unable to create dummy framebuffer");
  13279. }
  13280. this._dummyFramebuffer = dummy;
  13281. }
  13282. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13283. if (faceIndex > -1) {
  13284. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13285. }
  13286. else {
  13287. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13288. }
  13289. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13290. var buffer;
  13291. switch (readType) {
  13292. case gl.UNSIGNED_BYTE:
  13293. buffer = new Uint8Array(4 * width * height);
  13294. readType = gl.UNSIGNED_BYTE;
  13295. break;
  13296. default:
  13297. buffer = new Float32Array(4 * width * height);
  13298. readType = gl.FLOAT;
  13299. break;
  13300. }
  13301. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13302. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13303. return buffer;
  13304. };
  13305. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13306. if (this._webGLVersion > 1) {
  13307. return this._caps.colorBufferFloat;
  13308. }
  13309. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13310. };
  13311. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13312. if (this._webGLVersion > 1) {
  13313. return this._caps.colorBufferFloat;
  13314. }
  13315. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13316. };
  13317. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13318. Engine.prototype._canRenderToFramebuffer = function (type) {
  13319. var gl = this._gl;
  13320. //clear existing errors
  13321. while (gl.getError() !== gl.NO_ERROR) { }
  13322. var successful = true;
  13323. var texture = gl.createTexture();
  13324. gl.bindTexture(gl.TEXTURE_2D, texture);
  13325. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13328. var fb = gl.createFramebuffer();
  13329. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13330. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13331. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13332. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13333. successful = successful && (gl.getError() === gl.NO_ERROR);
  13334. //try render by clearing frame buffer's color buffer
  13335. if (successful) {
  13336. gl.clear(gl.COLOR_BUFFER_BIT);
  13337. successful = successful && (gl.getError() === gl.NO_ERROR);
  13338. }
  13339. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13340. if (successful) {
  13341. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13342. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13343. var readFormat = gl.RGBA;
  13344. var readType = gl.UNSIGNED_BYTE;
  13345. var buffer = new Uint8Array(4);
  13346. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13347. successful = successful && (gl.getError() === gl.NO_ERROR);
  13348. }
  13349. //clean up
  13350. gl.deleteTexture(texture);
  13351. gl.deleteFramebuffer(fb);
  13352. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13353. //clear accumulated errors
  13354. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13355. return successful;
  13356. };
  13357. Engine.prototype._getWebGLTextureType = function (type) {
  13358. if (type === Engine.TEXTURETYPE_FLOAT) {
  13359. return this._gl.FLOAT;
  13360. }
  13361. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13362. // Add Half Float Constant.
  13363. return this._gl.HALF_FLOAT_OES;
  13364. }
  13365. return this._gl.UNSIGNED_BYTE;
  13366. };
  13367. ;
  13368. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13369. if (this._webGLVersion === 1) {
  13370. return this._gl.RGBA;
  13371. }
  13372. if (type === Engine.TEXTURETYPE_FLOAT) {
  13373. return this._gl.RGBA32F;
  13374. }
  13375. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13376. return this._gl.RGBA16F;
  13377. }
  13378. return this._gl.RGBA;
  13379. };
  13380. ;
  13381. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13382. if (type === Engine.TEXTURETYPE_FLOAT) {
  13383. return this._gl.RGBA32F;
  13384. }
  13385. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13386. return this._gl.RGBA16F;
  13387. }
  13388. return this._gl.RGBA8;
  13389. };
  13390. ;
  13391. Engine.prototype.createQuery = function () {
  13392. return this._gl.createQuery();
  13393. };
  13394. Engine.prototype.deleteQuery = function (query) {
  13395. this._gl.deleteQuery(query);
  13396. return this;
  13397. };
  13398. Engine.prototype.isQueryResultAvailable = function (query) {
  13399. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13400. };
  13401. Engine.prototype.getQueryResult = function (query) {
  13402. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13403. };
  13404. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13405. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13406. this._gl.beginQuery(glAlgorithm, query);
  13407. return this;
  13408. };
  13409. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13410. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13411. this._gl.endQuery(glAlgorithm);
  13412. return this;
  13413. };
  13414. /* Time queries */
  13415. Engine.prototype._createTimeQuery = function () {
  13416. var timerQuery = this._caps.timerQuery;
  13417. if (timerQuery.createQueryEXT) {
  13418. return timerQuery.createQueryEXT();
  13419. }
  13420. return this.createQuery();
  13421. };
  13422. Engine.prototype._deleteTimeQuery = function (query) {
  13423. var timerQuery = this._caps.timerQuery;
  13424. if (timerQuery.deleteQueryEXT) {
  13425. timerQuery.deleteQueryEXT(query);
  13426. return;
  13427. }
  13428. this.deleteQuery(query);
  13429. };
  13430. Engine.prototype._getTimeQueryResult = function (query) {
  13431. var timerQuery = this._caps.timerQuery;
  13432. if (timerQuery.getQueryObjectEXT) {
  13433. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13434. }
  13435. return this.getQueryResult(query);
  13436. };
  13437. Engine.prototype._getTimeQueryAvailability = function (query) {
  13438. var timerQuery = this._caps.timerQuery;
  13439. if (timerQuery.getQueryObjectEXT) {
  13440. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13441. }
  13442. return this.isQueryResultAvailable(query);
  13443. };
  13444. Engine.prototype.startTimeQuery = function () {
  13445. var timerQuery = this._caps.timerQuery;
  13446. if (!timerQuery) {
  13447. return null;
  13448. }
  13449. var token = new BABYLON._TimeToken();
  13450. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13451. if (this._caps.canUseTimestampForTimerQuery) {
  13452. token._startTimeQuery = this._createTimeQuery();
  13453. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13454. }
  13455. else {
  13456. if (this._currentNonTimestampToken) {
  13457. return this._currentNonTimestampToken;
  13458. }
  13459. token._timeElapsedQuery = this._createTimeQuery();
  13460. if (timerQuery.beginQueryEXT) {
  13461. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13462. }
  13463. else {
  13464. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13465. }
  13466. this._currentNonTimestampToken = token;
  13467. }
  13468. return token;
  13469. };
  13470. Engine.prototype.endTimeQuery = function (token) {
  13471. var timerQuery = this._caps.timerQuery;
  13472. if (!timerQuery || !token) {
  13473. return -1;
  13474. }
  13475. if (this._caps.canUseTimestampForTimerQuery) {
  13476. if (!token._startTimeQuery) {
  13477. return -1;
  13478. }
  13479. if (!token._endTimeQuery) {
  13480. token._endTimeQuery = this._createTimeQuery();
  13481. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13482. }
  13483. }
  13484. else if (!token._timeElapsedQueryEnded) {
  13485. if (!token._timeElapsedQuery) {
  13486. return -1;
  13487. }
  13488. if (timerQuery.endQueryEXT) {
  13489. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13490. }
  13491. else {
  13492. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13493. }
  13494. token._timeElapsedQueryEnded = true;
  13495. }
  13496. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13497. var available = false;
  13498. if (token._endTimeQuery) {
  13499. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13500. }
  13501. else if (token._timeElapsedQuery) {
  13502. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13503. }
  13504. if (available && !disjoint) {
  13505. var result = 0;
  13506. if (this._caps.canUseTimestampForTimerQuery) {
  13507. if (!token._startTimeQuery || !token._endTimeQuery) {
  13508. return -1;
  13509. }
  13510. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13511. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13512. result = timeEnd - timeStart;
  13513. this._deleteTimeQuery(token._startTimeQuery);
  13514. this._deleteTimeQuery(token._endTimeQuery);
  13515. token._startTimeQuery = null;
  13516. token._endTimeQuery = null;
  13517. }
  13518. else {
  13519. if (!token._timeElapsedQuery) {
  13520. return -1;
  13521. }
  13522. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13523. this._deleteTimeQuery(token._timeElapsedQuery);
  13524. token._timeElapsedQuery = null;
  13525. token._timeElapsedQueryEnded = false;
  13526. this._currentNonTimestampToken = null;
  13527. }
  13528. return result;
  13529. }
  13530. return -1;
  13531. };
  13532. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13533. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13534. };
  13535. // Transform feedback
  13536. Engine.prototype.createTransformFeedback = function () {
  13537. return this._gl.createTransformFeedback();
  13538. };
  13539. Engine.prototype.deleteTransformFeedback = function (value) {
  13540. this._gl.deleteTransformFeedback(value);
  13541. };
  13542. Engine.prototype.bindTransformFeedback = function (value) {
  13543. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13544. };
  13545. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13546. if (usePoints === void 0) { usePoints = true; }
  13547. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13548. };
  13549. Engine.prototype.endTransformFeedback = function () {
  13550. this._gl.endTransformFeedback();
  13551. };
  13552. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13553. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13554. };
  13555. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13556. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13557. };
  13558. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13559. var _this = this;
  13560. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13561. this._activeRequests.push(request);
  13562. request.onCompleteObservable.add(function (request) {
  13563. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13564. });
  13565. return request;
  13566. };
  13567. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13568. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13569. var onload = function (data) {
  13570. loadedFiles[index] = data;
  13571. loadedFiles._internalCount++;
  13572. if (loadedFiles._internalCount === 6) {
  13573. onfinish(loadedFiles);
  13574. }
  13575. };
  13576. var onerror = function (request, exception) {
  13577. if (onErrorCallBack && request) {
  13578. onErrorCallBack(request.status + " " + request.statusText, exception);
  13579. }
  13580. };
  13581. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13582. };
  13583. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13584. if (onError === void 0) { onError = null; }
  13585. var loadedFiles = [];
  13586. loadedFiles._internalCount = 0;
  13587. for (var index = 0; index < 6; index++) {
  13588. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13589. }
  13590. };
  13591. // Statics
  13592. Engine.isSupported = function () {
  13593. try {
  13594. var tempcanvas = document.createElement("canvas");
  13595. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13596. return gl != null && !!window.WebGLRenderingContext;
  13597. }
  13598. catch (e) {
  13599. return false;
  13600. }
  13601. };
  13602. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13603. Engine.ExceptionList = [
  13604. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13605. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13606. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13607. ];
  13608. Engine.Instances = new Array();
  13609. // Const statics
  13610. Engine._ALPHA_DISABLE = 0;
  13611. Engine._ALPHA_ADD = 1;
  13612. Engine._ALPHA_COMBINE = 2;
  13613. Engine._ALPHA_SUBTRACT = 3;
  13614. Engine._ALPHA_MULTIPLY = 4;
  13615. Engine._ALPHA_MAXIMIZED = 5;
  13616. Engine._ALPHA_ONEONE = 6;
  13617. Engine._ALPHA_PREMULTIPLIED = 7;
  13618. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13619. Engine._ALPHA_INTERPOLATE = 9;
  13620. Engine._ALPHA_SCREENMODE = 10;
  13621. Engine._DELAYLOADSTATE_NONE = 0;
  13622. Engine._DELAYLOADSTATE_LOADED = 1;
  13623. Engine._DELAYLOADSTATE_LOADING = 2;
  13624. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13625. Engine._TEXTUREFORMAT_ALPHA = 0;
  13626. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13627. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13628. Engine._TEXTUREFORMAT_RGB = 4;
  13629. Engine._TEXTUREFORMAT_RGBA = 5;
  13630. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13631. Engine._TEXTURETYPE_FLOAT = 1;
  13632. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13633. // Depht or Stencil test Constants.
  13634. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13635. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  13636. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  13637. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  13638. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  13639. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  13640. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  13641. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  13642. // Stencil Actions Constants.
  13643. Engine._KEEP = 0x1E00;
  13644. Engine._REPLACE = 0x1E01;
  13645. Engine._INCR = 0x1E02;
  13646. Engine._DECR = 0x1E03;
  13647. Engine._INVERT = 0x150A;
  13648. Engine._INCR_WRAP = 0x8507;
  13649. Engine._DECR_WRAP = 0x8508;
  13650. // Texture rescaling mode
  13651. Engine._SCALEMODE_FLOOR = 1;
  13652. Engine._SCALEMODE_NEAREST = 2;
  13653. Engine._SCALEMODE_CEILING = 3;
  13654. // Updatable statics so stick with vars here
  13655. Engine.CollisionsEpsilon = 0.001;
  13656. Engine.CodeRepository = "src/";
  13657. Engine.ShadersRepository = "src/Shaders/";
  13658. return Engine;
  13659. }());
  13660. BABYLON.Engine = Engine;
  13661. })(BABYLON || (BABYLON = {}));
  13662. //# sourceMappingURL=babylon.engine.js.map
  13663. var BABYLON;
  13664. (function (BABYLON) {
  13665. /**
  13666. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13667. */
  13668. var Node = /** @class */ (function () {
  13669. /**
  13670. * @constructor
  13671. * @param {string} name - the name and id to be given to this node
  13672. * @param {BABYLON.Scene} the scene this node will be added to
  13673. */
  13674. function Node(name, scene) {
  13675. if (scene === void 0) { scene = null; }
  13676. this.state = "";
  13677. this.metadata = null;
  13678. this.doNotSerialize = false;
  13679. this.animations = new Array();
  13680. this._ranges = {};
  13681. this._isEnabled = true;
  13682. this._isReady = true;
  13683. this._currentRenderId = -1;
  13684. this._parentRenderId = -1;
  13685. /**
  13686. * An event triggered when the mesh is disposed.
  13687. * @type {BABYLON.Observable}
  13688. */
  13689. this.onDisposeObservable = new BABYLON.Observable();
  13690. // Behaviors
  13691. this._behaviors = new Array();
  13692. this.name = name;
  13693. this.id = name;
  13694. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13695. this.uniqueId = this._scene.getUniqueId();
  13696. this._initCache();
  13697. }
  13698. Object.defineProperty(Node.prototype, "parent", {
  13699. get: function () {
  13700. return this._parentNode;
  13701. },
  13702. set: function (parent) {
  13703. if (this._parentNode === parent) {
  13704. return;
  13705. }
  13706. // Remove self from list of children of parent
  13707. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13708. var index = this._parentNode._children.indexOf(this);
  13709. if (index !== -1) {
  13710. this._parentNode._children.splice(index, 1);
  13711. }
  13712. }
  13713. // Store new parent
  13714. this._parentNode = parent;
  13715. // Add as child to new parent
  13716. if (this._parentNode) {
  13717. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13718. this._parentNode._children = new Array();
  13719. }
  13720. this._parentNode._children.push(this);
  13721. }
  13722. },
  13723. enumerable: true,
  13724. configurable: true
  13725. });
  13726. Node.prototype.getClassName = function () {
  13727. return "Node";
  13728. };
  13729. Object.defineProperty(Node.prototype, "onDispose", {
  13730. set: function (callback) {
  13731. if (this._onDisposeObserver) {
  13732. this.onDisposeObservable.remove(this._onDisposeObserver);
  13733. }
  13734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Node.prototype.getScene = function () {
  13740. return this._scene;
  13741. };
  13742. Node.prototype.getEngine = function () {
  13743. return this._scene.getEngine();
  13744. };
  13745. Node.prototype.addBehavior = function (behavior) {
  13746. var _this = this;
  13747. var index = this._behaviors.indexOf(behavior);
  13748. if (index !== -1) {
  13749. return this;
  13750. }
  13751. behavior.init();
  13752. if (this._scene.isLoading) {
  13753. // We defer the attach when the scene will be loaded
  13754. var observer = this._scene.onDataLoadedObservable.add(function () {
  13755. behavior.attach(_this);
  13756. setTimeout(function () {
  13757. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13758. _this._scene.onDataLoadedObservable.remove(observer);
  13759. }, 0);
  13760. });
  13761. }
  13762. else {
  13763. behavior.attach(this);
  13764. }
  13765. this._behaviors.push(behavior);
  13766. return this;
  13767. };
  13768. Node.prototype.removeBehavior = function (behavior) {
  13769. var index = this._behaviors.indexOf(behavior);
  13770. if (index === -1) {
  13771. return this;
  13772. }
  13773. this._behaviors[index].detach();
  13774. this._behaviors.splice(index, 1);
  13775. return this;
  13776. };
  13777. Object.defineProperty(Node.prototype, "behaviors", {
  13778. get: function () {
  13779. return this._behaviors;
  13780. },
  13781. enumerable: true,
  13782. configurable: true
  13783. });
  13784. Node.prototype.getBehaviorByName = function (name) {
  13785. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13786. var behavior = _a[_i];
  13787. if (behavior.name === name) {
  13788. return behavior;
  13789. }
  13790. }
  13791. return null;
  13792. };
  13793. // override it in derived class
  13794. Node.prototype.getWorldMatrix = function () {
  13795. return BABYLON.Matrix.Identity();
  13796. };
  13797. // override it in derived class if you add new variables to the cache
  13798. // and call the parent class method
  13799. Node.prototype._initCache = function () {
  13800. this._cache = {};
  13801. this._cache.parent = undefined;
  13802. };
  13803. Node.prototype.updateCache = function (force) {
  13804. if (!force && this.isSynchronized())
  13805. return;
  13806. this._cache.parent = this.parent;
  13807. this._updateCache();
  13808. };
  13809. // override it in derived class if you add new variables to the cache
  13810. // and call the parent class method if !ignoreParentClass
  13811. Node.prototype._updateCache = function (ignoreParentClass) {
  13812. };
  13813. // override it in derived class if you add new variables to the cache
  13814. Node.prototype._isSynchronized = function () {
  13815. return true;
  13816. };
  13817. Node.prototype._markSyncedWithParent = function () {
  13818. if (this.parent) {
  13819. this._parentRenderId = this.parent._currentRenderId;
  13820. }
  13821. };
  13822. Node.prototype.isSynchronizedWithParent = function () {
  13823. if (!this.parent) {
  13824. return true;
  13825. }
  13826. if (this._parentRenderId !== this.parent._currentRenderId) {
  13827. return false;
  13828. }
  13829. return this.parent.isSynchronized();
  13830. };
  13831. Node.prototype.isSynchronized = function (updateCache) {
  13832. var check = this.hasNewParent();
  13833. check = check || !this.isSynchronizedWithParent();
  13834. check = check || !this._isSynchronized();
  13835. if (updateCache)
  13836. this.updateCache(true);
  13837. return !check;
  13838. };
  13839. Node.prototype.hasNewParent = function (update) {
  13840. if (this._cache.parent === this.parent)
  13841. return false;
  13842. if (update)
  13843. this._cache.parent = this.parent;
  13844. return true;
  13845. };
  13846. /**
  13847. * Is this node ready to be used/rendered
  13848. * @return {boolean} is it ready
  13849. */
  13850. Node.prototype.isReady = function () {
  13851. return this._isReady;
  13852. };
  13853. /**
  13854. * Is this node enabled.
  13855. * 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.
  13856. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13857. * @return {boolean} whether this node (and its parent) is enabled.
  13858. * @see setEnabled
  13859. */
  13860. Node.prototype.isEnabled = function (checkAncestors) {
  13861. if (checkAncestors === void 0) { checkAncestors = true; }
  13862. if (checkAncestors === false) {
  13863. return this._isEnabled;
  13864. }
  13865. if (this._isEnabled === false) {
  13866. return false;
  13867. }
  13868. if (this.parent !== undefined && this.parent !== null) {
  13869. return this.parent.isEnabled(checkAncestors);
  13870. }
  13871. return true;
  13872. };
  13873. /**
  13874. * Set the enabled state of this node.
  13875. * @param {boolean} value - the new enabled state
  13876. * @see isEnabled
  13877. */
  13878. Node.prototype.setEnabled = function (value) {
  13879. this._isEnabled = value;
  13880. };
  13881. /**
  13882. * Is this node a descendant of the given node.
  13883. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13884. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13885. * @see parent
  13886. */
  13887. Node.prototype.isDescendantOf = function (ancestor) {
  13888. if (this.parent) {
  13889. if (this.parent === ancestor) {
  13890. return true;
  13891. }
  13892. return this.parent.isDescendantOf(ancestor);
  13893. }
  13894. return false;
  13895. };
  13896. /**
  13897. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13898. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13899. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13900. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13901. */
  13902. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13903. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13904. if (!this._children) {
  13905. return;
  13906. }
  13907. for (var index = 0; index < this._children.length; index++) {
  13908. var item = this._children[index];
  13909. if (!predicate || predicate(item)) {
  13910. results.push(item);
  13911. }
  13912. if (!directDescendantsOnly) {
  13913. item._getDescendants(results, false, predicate);
  13914. }
  13915. }
  13916. };
  13917. /**
  13918. * Will return all nodes that have this node as ascendant.
  13919. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13920. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13921. * @return {BABYLON.Node[]} all children nodes of all types.
  13922. */
  13923. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13924. var results = new Array();
  13925. this._getDescendants(results, directDescendantsOnly, predicate);
  13926. return results;
  13927. };
  13928. /**
  13929. * Get all child-meshes of this node.
  13930. */
  13931. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13932. var results = [];
  13933. this._getDescendants(results, directDescendantsOnly, function (node) {
  13934. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13935. });
  13936. return results;
  13937. };
  13938. /**
  13939. * Get all child-transformNodes of this node.
  13940. */
  13941. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13942. var results = [];
  13943. this._getDescendants(results, directDescendantsOnly, function (node) {
  13944. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13945. });
  13946. return results;
  13947. };
  13948. /**
  13949. * Get all direct children of this node.
  13950. */
  13951. Node.prototype.getChildren = function (predicate) {
  13952. return this.getDescendants(true, predicate);
  13953. };
  13954. Node.prototype._setReady = function (state) {
  13955. if (state === this._isReady) {
  13956. return;
  13957. }
  13958. if (!state) {
  13959. this._isReady = false;
  13960. return;
  13961. }
  13962. this._isReady = true;
  13963. if (this.onReady) {
  13964. this.onReady(this);
  13965. }
  13966. };
  13967. Node.prototype.getAnimationByName = function (name) {
  13968. for (var i = 0; i < this.animations.length; i++) {
  13969. var animation = this.animations[i];
  13970. if (animation.name === name) {
  13971. return animation;
  13972. }
  13973. }
  13974. return null;
  13975. };
  13976. Node.prototype.createAnimationRange = function (name, from, to) {
  13977. // check name not already in use
  13978. if (!this._ranges[name]) {
  13979. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13980. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13981. if (this.animations[i]) {
  13982. this.animations[i].createRange(name, from, to);
  13983. }
  13984. }
  13985. }
  13986. };
  13987. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13988. if (deleteFrames === void 0) { deleteFrames = true; }
  13989. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13990. if (this.animations[i]) {
  13991. this.animations[i].deleteRange(name, deleteFrames);
  13992. }
  13993. }
  13994. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13995. };
  13996. Node.prototype.getAnimationRange = function (name) {
  13997. return this._ranges[name];
  13998. };
  13999. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14000. var range = this.getAnimationRange(name);
  14001. if (!range) {
  14002. return;
  14003. }
  14004. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14005. };
  14006. Node.prototype.serializeAnimationRanges = function () {
  14007. var serializationRanges = [];
  14008. for (var name in this._ranges) {
  14009. var localRange = this._ranges[name];
  14010. if (!localRange) {
  14011. continue;
  14012. }
  14013. var range = {};
  14014. range.name = name;
  14015. range.from = localRange.from;
  14016. range.to = localRange.to;
  14017. serializationRanges.push(range);
  14018. }
  14019. return serializationRanges;
  14020. };
  14021. // override it in derived class
  14022. Node.prototype.computeWorldMatrix = function (force) {
  14023. return BABYLON.Matrix.Identity();
  14024. };
  14025. Node.prototype.dispose = function () {
  14026. this.parent = null;
  14027. // Callback
  14028. this.onDisposeObservable.notifyObservers(this);
  14029. this.onDisposeObservable.clear();
  14030. // Behaviors
  14031. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14032. var behavior = _a[_i];
  14033. behavior.detach();
  14034. }
  14035. this._behaviors = [];
  14036. };
  14037. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14038. if (parsedNode.ranges) {
  14039. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14040. var data = parsedNode.ranges[index];
  14041. node.createAnimationRange(data.name, data.from, data.to);
  14042. }
  14043. }
  14044. };
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], Node.prototype, "name", void 0);
  14048. __decorate([
  14049. BABYLON.serialize()
  14050. ], Node.prototype, "id", void 0);
  14051. __decorate([
  14052. BABYLON.serialize()
  14053. ], Node.prototype, "uniqueId", void 0);
  14054. __decorate([
  14055. BABYLON.serialize()
  14056. ], Node.prototype, "state", void 0);
  14057. __decorate([
  14058. BABYLON.serialize()
  14059. ], Node.prototype, "metadata", void 0);
  14060. return Node;
  14061. }());
  14062. BABYLON.Node = Node;
  14063. })(BABYLON || (BABYLON = {}));
  14064. //# sourceMappingURL=babylon.node.js.map
  14065. var BABYLON;
  14066. (function (BABYLON) {
  14067. var BoundingSphere = /** @class */ (function () {
  14068. function BoundingSphere(minimum, maximum) {
  14069. this.minimum = minimum;
  14070. this.maximum = maximum;
  14071. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14072. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14073. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14074. this.radius = distance * 0.5;
  14075. this.centerWorld = BABYLON.Vector3.Zero();
  14076. this._update(BABYLON.Matrix.Identity());
  14077. }
  14078. // Methods
  14079. BoundingSphere.prototype._update = function (world) {
  14080. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14081. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14082. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14083. };
  14084. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14085. for (var i = 0; i < 6; i++) {
  14086. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14087. return false;
  14088. }
  14089. return true;
  14090. };
  14091. BoundingSphere.prototype.intersectsPoint = function (point) {
  14092. var x = this.centerWorld.x - point.x;
  14093. var y = this.centerWorld.y - point.y;
  14094. var z = this.centerWorld.z - point.z;
  14095. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14096. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14097. return false;
  14098. return true;
  14099. };
  14100. // Statics
  14101. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14102. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14103. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14104. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14105. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14106. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14107. return false;
  14108. return true;
  14109. };
  14110. return BoundingSphere;
  14111. }());
  14112. BABYLON.BoundingSphere = BoundingSphere;
  14113. })(BABYLON || (BABYLON = {}));
  14114. //# sourceMappingURL=babylon.boundingSphere.js.map
  14115. var BABYLON;
  14116. (function (BABYLON) {
  14117. var BoundingBox = /** @class */ (function () {
  14118. function BoundingBox(minimum, maximum) {
  14119. this.minimum = minimum;
  14120. this.maximum = maximum;
  14121. this.vectors = new Array();
  14122. this.vectorsWorld = new Array();
  14123. // Bounding vectors
  14124. this.vectors.push(this.minimum.clone());
  14125. this.vectors.push(this.maximum.clone());
  14126. this.vectors.push(this.minimum.clone());
  14127. this.vectors[2].x = this.maximum.x;
  14128. this.vectors.push(this.minimum.clone());
  14129. this.vectors[3].y = this.maximum.y;
  14130. this.vectors.push(this.minimum.clone());
  14131. this.vectors[4].z = this.maximum.z;
  14132. this.vectors.push(this.maximum.clone());
  14133. this.vectors[5].z = this.minimum.z;
  14134. this.vectors.push(this.maximum.clone());
  14135. this.vectors[6].x = this.minimum.x;
  14136. this.vectors.push(this.maximum.clone());
  14137. this.vectors[7].y = this.minimum.y;
  14138. // OBB
  14139. this.center = this.maximum.add(this.minimum).scale(0.5);
  14140. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14141. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14142. // World
  14143. for (var index = 0; index < this.vectors.length; index++) {
  14144. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14145. }
  14146. this.minimumWorld = BABYLON.Vector3.Zero();
  14147. this.maximumWorld = BABYLON.Vector3.Zero();
  14148. this.centerWorld = BABYLON.Vector3.Zero();
  14149. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14150. this._update(BABYLON.Matrix.Identity());
  14151. }
  14152. // Methods
  14153. BoundingBox.prototype.getWorldMatrix = function () {
  14154. return this._worldMatrix;
  14155. };
  14156. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14157. this._worldMatrix.copyFrom(matrix);
  14158. return this;
  14159. };
  14160. BoundingBox.prototype._update = function (world) {
  14161. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14162. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14163. for (var index = 0; index < this.vectors.length; index++) {
  14164. var v = this.vectorsWorld[index];
  14165. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14166. if (v.x < this.minimumWorld.x)
  14167. this.minimumWorld.x = v.x;
  14168. if (v.y < this.minimumWorld.y)
  14169. this.minimumWorld.y = v.y;
  14170. if (v.z < this.minimumWorld.z)
  14171. this.minimumWorld.z = v.z;
  14172. if (v.x > this.maximumWorld.x)
  14173. this.maximumWorld.x = v.x;
  14174. if (v.y > this.maximumWorld.y)
  14175. this.maximumWorld.y = v.y;
  14176. if (v.z > this.maximumWorld.z)
  14177. this.maximumWorld.z = v.z;
  14178. }
  14179. // Extend
  14180. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14181. this.extendSizeWorld.scaleInPlace(0.5);
  14182. // OBB
  14183. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14184. this.centerWorld.scaleInPlace(0.5);
  14185. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14186. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14187. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14188. this._worldMatrix = world;
  14189. };
  14190. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14191. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14192. };
  14193. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14194. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14195. };
  14196. BoundingBox.prototype.intersectsPoint = function (point) {
  14197. var delta = -BABYLON.Epsilon;
  14198. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14199. return false;
  14200. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14201. return false;
  14202. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14203. return false;
  14204. return true;
  14205. };
  14206. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14207. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14208. };
  14209. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14210. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14211. return false;
  14212. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14213. return false;
  14214. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14215. return false;
  14216. return true;
  14217. };
  14218. // Statics
  14219. BoundingBox.Intersects = function (box0, box1) {
  14220. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14221. return false;
  14222. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14223. return false;
  14224. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14225. return false;
  14226. return true;
  14227. };
  14228. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14229. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14230. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14231. return (num <= (sphereRadius * sphereRadius));
  14232. };
  14233. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14234. for (var p = 0; p < 6; p++) {
  14235. for (var i = 0; i < 8; i++) {
  14236. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14237. return false;
  14238. }
  14239. }
  14240. }
  14241. return true;
  14242. };
  14243. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14244. for (var p = 0; p < 6; p++) {
  14245. var inCount = 8;
  14246. for (var i = 0; i < 8; i++) {
  14247. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14248. --inCount;
  14249. }
  14250. else {
  14251. break;
  14252. }
  14253. }
  14254. if (inCount === 0)
  14255. return false;
  14256. }
  14257. return true;
  14258. };
  14259. return BoundingBox;
  14260. }());
  14261. BABYLON.BoundingBox = BoundingBox;
  14262. })(BABYLON || (BABYLON = {}));
  14263. //# sourceMappingURL=babylon.boundingBox.js.map
  14264. var BABYLON;
  14265. (function (BABYLON) {
  14266. var computeBoxExtents = function (axis, box) {
  14267. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14268. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14269. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14270. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14271. var r = r0 + r1 + r2;
  14272. return {
  14273. min: p - r,
  14274. max: p + r
  14275. };
  14276. };
  14277. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14278. var axisOverlap = function (axis, box0, box1) {
  14279. var result0 = computeBoxExtents(axis, box0);
  14280. var result1 = computeBoxExtents(axis, box1);
  14281. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14282. };
  14283. var BoundingInfo = /** @class */ (function () {
  14284. function BoundingInfo(minimum, maximum) {
  14285. this.minimum = minimum;
  14286. this.maximum = maximum;
  14287. this._isLocked = false;
  14288. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14289. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14290. }
  14291. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14292. get: function () {
  14293. return this._isLocked;
  14294. },
  14295. set: function (value) {
  14296. this._isLocked = value;
  14297. },
  14298. enumerable: true,
  14299. configurable: true
  14300. });
  14301. // Methods
  14302. BoundingInfo.prototype.update = function (world) {
  14303. if (this._isLocked) {
  14304. return;
  14305. }
  14306. this.boundingBox._update(world);
  14307. this.boundingSphere._update(world);
  14308. };
  14309. /**
  14310. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14311. * @param center New center of the bounding info
  14312. * @param extend New extend of the bounding info
  14313. */
  14314. BoundingInfo.prototype.centerOn = function (center, extend) {
  14315. this.minimum = center.subtract(extend);
  14316. this.maximum = center.add(extend);
  14317. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14318. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14319. return this;
  14320. };
  14321. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14322. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14323. return false;
  14324. return this.boundingBox.isInFrustum(frustumPlanes);
  14325. };
  14326. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14327. /**
  14328. * Gets the world distance between the min and max points of the bounding box
  14329. */
  14330. get: function () {
  14331. var boundingBox = this.boundingBox;
  14332. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14333. return size.length();
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14339. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14340. };
  14341. BoundingInfo.prototype._checkCollision = function (collider) {
  14342. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14343. };
  14344. BoundingInfo.prototype.intersectsPoint = function (point) {
  14345. if (!this.boundingSphere.centerWorld) {
  14346. return false;
  14347. }
  14348. if (!this.boundingSphere.intersectsPoint(point)) {
  14349. return false;
  14350. }
  14351. if (!this.boundingBox.intersectsPoint(point)) {
  14352. return false;
  14353. }
  14354. return true;
  14355. };
  14356. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14357. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14358. return false;
  14359. }
  14360. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14361. return false;
  14362. }
  14363. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14364. return false;
  14365. }
  14366. if (!precise) {
  14367. return true;
  14368. }
  14369. var box0 = this.boundingBox;
  14370. var box1 = boundingInfo.boundingBox;
  14371. if (!axisOverlap(box0.directions[0], box0, box1))
  14372. return false;
  14373. if (!axisOverlap(box0.directions[1], box0, box1))
  14374. return false;
  14375. if (!axisOverlap(box0.directions[2], box0, box1))
  14376. return false;
  14377. if (!axisOverlap(box1.directions[0], box0, box1))
  14378. return false;
  14379. if (!axisOverlap(box1.directions[1], box0, box1))
  14380. return false;
  14381. if (!axisOverlap(box1.directions[2], box0, box1))
  14382. return false;
  14383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14384. return false;
  14385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14386. return false;
  14387. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14388. return false;
  14389. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14390. return false;
  14391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14392. return false;
  14393. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14394. return false;
  14395. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14396. return false;
  14397. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14398. return false;
  14399. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14400. return false;
  14401. return true;
  14402. };
  14403. return BoundingInfo;
  14404. }());
  14405. BABYLON.BoundingInfo = BoundingInfo;
  14406. })(BABYLON || (BABYLON = {}));
  14407. //# sourceMappingURL=babylon.boundingInfo.js.map
  14408. var BABYLON;
  14409. (function (BABYLON) {
  14410. var TransformNode = /** @class */ (function (_super) {
  14411. __extends(TransformNode, _super);
  14412. function TransformNode(name, scene, isPure) {
  14413. if (scene === void 0) { scene = null; }
  14414. if (isPure === void 0) { isPure = true; }
  14415. var _this = _super.call(this, name, scene) || this;
  14416. // Properties
  14417. _this._rotation = BABYLON.Vector3.Zero();
  14418. _this._scaling = BABYLON.Vector3.One();
  14419. _this._isDirty = false;
  14420. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14421. _this.scalingDeterminant = 1;
  14422. _this.infiniteDistance = false;
  14423. _this.position = BABYLON.Vector3.Zero();
  14424. _this._localWorld = BABYLON.Matrix.Zero();
  14425. _this._worldMatrix = BABYLON.Matrix.Zero();
  14426. _this._worldMatrixDeterminant = 0;
  14427. _this._absolutePosition = BABYLON.Vector3.Zero();
  14428. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14429. _this._postMultiplyPivotMatrix = false;
  14430. _this._isWorldMatrixFrozen = false;
  14431. /**
  14432. * An event triggered after the world matrix is updated
  14433. * @type {BABYLON.Observable}
  14434. */
  14435. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14436. _this._nonUniformScaling = false;
  14437. if (isPure) {
  14438. _this.getScene().addTransformNode(_this);
  14439. }
  14440. return _this;
  14441. }
  14442. Object.defineProperty(TransformNode.prototype, "rotation", {
  14443. /**
  14444. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14445. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14446. * Default : (0.0, 0.0, 0.0)
  14447. */
  14448. get: function () {
  14449. return this._rotation;
  14450. },
  14451. set: function (newRotation) {
  14452. this._rotation = newRotation;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(TransformNode.prototype, "scaling", {
  14458. /**
  14459. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14460. * Default : (1.0, 1.0, 1.0)
  14461. */
  14462. get: function () {
  14463. return this._scaling;
  14464. },
  14465. /**
  14466. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14467. * Default : (1.0, 1.0, 1.0)
  14468. */
  14469. set: function (newScaling) {
  14470. this._scaling = newScaling;
  14471. },
  14472. enumerable: true,
  14473. configurable: true
  14474. });
  14475. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14476. /**
  14477. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14478. * It's null by default.
  14479. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  14480. */
  14481. get: function () {
  14482. return this._rotationQuaternion;
  14483. },
  14484. set: function (quaternion) {
  14485. this._rotationQuaternion = quaternion;
  14486. //reset the rotation vector.
  14487. if (quaternion && this.rotation.length()) {
  14488. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14489. }
  14490. },
  14491. enumerable: true,
  14492. configurable: true
  14493. });
  14494. /**
  14495. * Returns the latest update of the World matrix
  14496. * Returns a Matrix.
  14497. */
  14498. TransformNode.prototype.getWorldMatrix = function () {
  14499. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14500. this.computeWorldMatrix();
  14501. }
  14502. return this._worldMatrix;
  14503. };
  14504. /**
  14505. * Returns the latest update of the World matrix determinant.
  14506. */
  14507. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14508. return this._worldMatrixDeterminant;
  14509. };
  14510. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14511. /**
  14512. * Returns directly the latest state of the mesh World matrix.
  14513. * A Matrix is returned.
  14514. */
  14515. get: function () {
  14516. return this._worldMatrix;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. /**
  14522. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14523. * Returns the AbstractMesh.
  14524. */
  14525. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14526. this._poseMatrix.copyFrom(matrix);
  14527. return this;
  14528. };
  14529. /**
  14530. * Returns the mesh Pose matrix.
  14531. * Returned object : Matrix
  14532. */
  14533. TransformNode.prototype.getPoseMatrix = function () {
  14534. return this._poseMatrix;
  14535. };
  14536. TransformNode.prototype._isSynchronized = function () {
  14537. if (this._isDirty) {
  14538. return false;
  14539. }
  14540. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14541. return false;
  14542. if (this._cache.pivotMatrixUpdated) {
  14543. return false;
  14544. }
  14545. if (this.infiniteDistance) {
  14546. return false;
  14547. }
  14548. if (!this._cache.position.equals(this.position))
  14549. return false;
  14550. if (this.rotationQuaternion) {
  14551. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14552. return false;
  14553. }
  14554. if (!this._cache.rotation.equals(this.rotation))
  14555. return false;
  14556. if (!this._cache.scaling.equals(this.scaling))
  14557. return false;
  14558. return true;
  14559. };
  14560. TransformNode.prototype._initCache = function () {
  14561. _super.prototype._initCache.call(this);
  14562. this._cache.localMatrixUpdated = false;
  14563. this._cache.position = BABYLON.Vector3.Zero();
  14564. this._cache.scaling = BABYLON.Vector3.Zero();
  14565. this._cache.rotation = BABYLON.Vector3.Zero();
  14566. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14567. this._cache.billboardMode = -1;
  14568. };
  14569. TransformNode.prototype.markAsDirty = function (property) {
  14570. if (property === "rotation") {
  14571. this.rotationQuaternion = null;
  14572. }
  14573. this._currentRenderId = Number.MAX_VALUE;
  14574. this._isDirty = true;
  14575. return this;
  14576. };
  14577. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14578. /**
  14579. * Returns the current mesh absolute position.
  14580. * Retuns a Vector3.
  14581. */
  14582. get: function () {
  14583. return this._absolutePosition;
  14584. },
  14585. enumerable: true,
  14586. configurable: true
  14587. });
  14588. /**
  14589. * Sets a new pivot matrix to the mesh.
  14590. * Returns the AbstractMesh.
  14591. */
  14592. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14593. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14594. this._pivotMatrix = matrix.clone();
  14595. this._cache.pivotMatrixUpdated = true;
  14596. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14597. if (this._postMultiplyPivotMatrix) {
  14598. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14599. }
  14600. return this;
  14601. };
  14602. /**
  14603. * Returns the mesh pivot matrix.
  14604. * Default : Identity.
  14605. * A Matrix is returned.
  14606. */
  14607. TransformNode.prototype.getPivotMatrix = function () {
  14608. return this._pivotMatrix;
  14609. };
  14610. /**
  14611. * Prevents the World matrix to be computed any longer.
  14612. * Returns the AbstractMesh.
  14613. */
  14614. TransformNode.prototype.freezeWorldMatrix = function () {
  14615. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14616. this.computeWorldMatrix(true);
  14617. this._isWorldMatrixFrozen = true;
  14618. return this;
  14619. };
  14620. /**
  14621. * Allows back the World matrix computation.
  14622. * Returns the AbstractMesh.
  14623. */
  14624. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14625. this._isWorldMatrixFrozen = false;
  14626. this.computeWorldMatrix(true);
  14627. return this;
  14628. };
  14629. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14630. /**
  14631. * True if the World matrix has been frozen.
  14632. * Returns a boolean.
  14633. */
  14634. get: function () {
  14635. return this._isWorldMatrixFrozen;
  14636. },
  14637. enumerable: true,
  14638. configurable: true
  14639. });
  14640. /**
  14641. * Retuns the mesh absolute position in the World.
  14642. * Returns a Vector3.
  14643. */
  14644. TransformNode.prototype.getAbsolutePosition = function () {
  14645. this.computeWorldMatrix();
  14646. return this._absolutePosition;
  14647. };
  14648. /**
  14649. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14650. * Returns the AbstractMesh.
  14651. */
  14652. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14653. if (!absolutePosition) {
  14654. return this;
  14655. }
  14656. var absolutePositionX;
  14657. var absolutePositionY;
  14658. var absolutePositionZ;
  14659. if (absolutePosition.x === undefined) {
  14660. if (arguments.length < 3) {
  14661. return this;
  14662. }
  14663. absolutePositionX = arguments[0];
  14664. absolutePositionY = arguments[1];
  14665. absolutePositionZ = arguments[2];
  14666. }
  14667. else {
  14668. absolutePositionX = absolutePosition.x;
  14669. absolutePositionY = absolutePosition.y;
  14670. absolutePositionZ = absolutePosition.z;
  14671. }
  14672. if (this.parent) {
  14673. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14674. invertParentWorldMatrix.invert();
  14675. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14676. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14677. }
  14678. else {
  14679. this.position.x = absolutePositionX;
  14680. this.position.y = absolutePositionY;
  14681. this.position.z = absolutePositionZ;
  14682. }
  14683. return this;
  14684. };
  14685. /**
  14686. * Sets the mesh position in its local space.
  14687. * Returns the AbstractMesh.
  14688. */
  14689. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14690. this.computeWorldMatrix();
  14691. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14692. return this;
  14693. };
  14694. /**
  14695. * Returns the mesh position in the local space from the current World matrix values.
  14696. * Returns a new Vector3.
  14697. */
  14698. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14699. this.computeWorldMatrix();
  14700. var invLocalWorldMatrix = this._localWorld.clone();
  14701. invLocalWorldMatrix.invert();
  14702. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14703. };
  14704. /**
  14705. * Translates the mesh along the passed Vector3 in its local space.
  14706. * Returns the AbstractMesh.
  14707. */
  14708. TransformNode.prototype.locallyTranslate = function (vector3) {
  14709. this.computeWorldMatrix(true);
  14710. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14711. return this;
  14712. };
  14713. /**
  14714. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14715. * @param targetPoint the position (must be in same space as current mesh) to look at
  14716. * @param yawCor optional yaw (y-axis) correction in radians
  14717. * @param pitchCor optional pitch (x-axis) correction in radians
  14718. * @param rollCor optional roll (z-axis) correction in radians
  14719. * @param space the choosen space of the target
  14720. * @returns the TransformNode.
  14721. */
  14722. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14723. if (yawCor === void 0) { yawCor = 0; }
  14724. if (pitchCor === void 0) { pitchCor = 0; }
  14725. if (rollCor === void 0) { rollCor = 0; }
  14726. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14727. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14728. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14729. targetPoint.subtractToRef(pos, dv);
  14730. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14731. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14732. var pitch = Math.atan2(dv.y, len);
  14733. if (this.rotationQuaternion) {
  14734. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14735. }
  14736. else {
  14737. this.rotation.x = pitch + pitchCor;
  14738. this.rotation.y = yaw + yawCor;
  14739. this.rotation.z = rollCor;
  14740. }
  14741. return this;
  14742. };
  14743. /**
  14744. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14745. * This Vector3 is expressed in the World space.
  14746. */
  14747. TransformNode.prototype.getDirection = function (localAxis) {
  14748. var result = BABYLON.Vector3.Zero();
  14749. this.getDirectionToRef(localAxis, result);
  14750. return result;
  14751. };
  14752. /**
  14753. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14754. * localAxis is expressed in the mesh local space.
  14755. * result is computed in the Wordl space from the mesh World matrix.
  14756. * Returns the AbstractMesh.
  14757. */
  14758. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14759. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14760. return this;
  14761. };
  14762. TransformNode.prototype.setPivotPoint = function (point, space) {
  14763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14764. if (this.getScene().getRenderId() == 0) {
  14765. this.computeWorldMatrix(true);
  14766. }
  14767. var wm = this.getWorldMatrix();
  14768. if (space == BABYLON.Space.WORLD) {
  14769. var tmat = BABYLON.Tmp.Matrix[0];
  14770. wm.invertToRef(tmat);
  14771. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14772. }
  14773. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14774. this._pivotMatrix.m[12] = -point.x;
  14775. this._pivotMatrix.m[13] = -point.y;
  14776. this._pivotMatrix.m[14] = -point.z;
  14777. this._cache.pivotMatrixUpdated = true;
  14778. return this;
  14779. };
  14780. /**
  14781. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14782. */
  14783. TransformNode.prototype.getPivotPoint = function () {
  14784. var point = BABYLON.Vector3.Zero();
  14785. this.getPivotPointToRef(point);
  14786. return point;
  14787. };
  14788. /**
  14789. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14790. * Returns the AbstractMesh.
  14791. */
  14792. TransformNode.prototype.getPivotPointToRef = function (result) {
  14793. result.x = -this._pivotMatrix.m[12];
  14794. result.y = -this._pivotMatrix.m[13];
  14795. result.z = -this._pivotMatrix.m[14];
  14796. return this;
  14797. };
  14798. /**
  14799. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14800. */
  14801. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14802. var point = BABYLON.Vector3.Zero();
  14803. this.getAbsolutePivotPointToRef(point);
  14804. return point;
  14805. };
  14806. /**
  14807. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14808. * Returns the AbstractMesh.
  14809. */
  14810. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14811. result.x = this._pivotMatrix.m[12];
  14812. result.y = this._pivotMatrix.m[13];
  14813. result.z = this._pivotMatrix.m[14];
  14814. this.getPivotPointToRef(result);
  14815. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14816. return this;
  14817. };
  14818. /**
  14819. * Defines the passed node as the parent of the current node.
  14820. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14821. * Returns the TransformNode.
  14822. */
  14823. TransformNode.prototype.setParent = function (node) {
  14824. if (node === null) {
  14825. var rotation = BABYLON.Tmp.Quaternion[0];
  14826. var position = BABYLON.Tmp.Vector3[0];
  14827. var scale = BABYLON.Tmp.Vector3[1];
  14828. if (this.parent && this.parent.computeWorldMatrix) {
  14829. this.parent.computeWorldMatrix(true);
  14830. }
  14831. this.computeWorldMatrix(true);
  14832. this.getWorldMatrix().decompose(scale, rotation, position);
  14833. if (this.rotationQuaternion) {
  14834. this.rotationQuaternion.copyFrom(rotation);
  14835. }
  14836. else {
  14837. rotation.toEulerAnglesToRef(this.rotation);
  14838. }
  14839. this.scaling.x = scale.x;
  14840. this.scaling.y = scale.y;
  14841. this.scaling.z = scale.z;
  14842. this.position.x = position.x;
  14843. this.position.y = position.y;
  14844. this.position.z = position.z;
  14845. }
  14846. else {
  14847. var rotation = BABYLON.Tmp.Quaternion[0];
  14848. var position = BABYLON.Tmp.Vector3[0];
  14849. var scale = BABYLON.Tmp.Vector3[1];
  14850. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14851. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14852. this.computeWorldMatrix(true);
  14853. node.computeWorldMatrix(true);
  14854. node.getWorldMatrix().invertToRef(invParentMatrix);
  14855. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14856. diffMatrix.decompose(scale, rotation, position);
  14857. if (this.rotationQuaternion) {
  14858. this.rotationQuaternion.copyFrom(rotation);
  14859. }
  14860. else {
  14861. rotation.toEulerAnglesToRef(this.rotation);
  14862. }
  14863. this.position.x = position.x;
  14864. this.position.y = position.y;
  14865. this.position.z = position.z;
  14866. this.scaling.x = scale.x;
  14867. this.scaling.y = scale.y;
  14868. this.scaling.z = scale.z;
  14869. }
  14870. this.parent = node;
  14871. return this;
  14872. };
  14873. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14874. get: function () {
  14875. return this._nonUniformScaling;
  14876. },
  14877. enumerable: true,
  14878. configurable: true
  14879. });
  14880. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14881. if (this._nonUniformScaling === value) {
  14882. return false;
  14883. }
  14884. this._nonUniformScaling = true;
  14885. return true;
  14886. };
  14887. /**
  14888. * Attach the current TransformNode to another TransformNode associated with a bone
  14889. * @param bone Bone affecting the TransformNode
  14890. * @param affectedTransformNode TransformNode associated with the bone
  14891. */
  14892. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14893. this._transformToBoneReferal = affectedTransformNode;
  14894. this.parent = bone;
  14895. if (bone.getWorldMatrix().determinant() < 0) {
  14896. this.scalingDeterminant *= -1;
  14897. }
  14898. return this;
  14899. };
  14900. TransformNode.prototype.detachFromBone = function () {
  14901. if (!this.parent) {
  14902. return this;
  14903. }
  14904. if (this.parent.getWorldMatrix().determinant() < 0) {
  14905. this.scalingDeterminant *= -1;
  14906. }
  14907. this._transformToBoneReferal = null;
  14908. this.parent = null;
  14909. return this;
  14910. };
  14911. /**
  14912. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14913. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14914. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14915. * The passed axis is also normalized.
  14916. * Returns the AbstractMesh.
  14917. */
  14918. TransformNode.prototype.rotate = function (axis, amount, space) {
  14919. axis.normalize();
  14920. if (!this.rotationQuaternion) {
  14921. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14922. this.rotation = BABYLON.Vector3.Zero();
  14923. }
  14924. var rotationQuaternion;
  14925. if (!space || space === BABYLON.Space.LOCAL) {
  14926. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14927. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14928. }
  14929. else {
  14930. if (this.parent) {
  14931. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14932. invertParentWorldMatrix.invert();
  14933. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14934. }
  14935. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14936. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14937. }
  14938. return this;
  14939. };
  14940. /**
  14941. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14942. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14943. * The passed axis is also normalized.
  14944. * Returns the AbstractMesh.
  14945. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14946. */
  14947. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14948. axis.normalize();
  14949. if (!this.rotationQuaternion) {
  14950. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14951. this.rotation.copyFromFloats(0, 0, 0);
  14952. }
  14953. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14954. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14955. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14956. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14957. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14958. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14959. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14960. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14961. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14962. return this;
  14963. };
  14964. /**
  14965. * Translates the mesh along the axis vector for the passed distance in the given space.
  14966. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14967. * Returns the AbstractMesh.
  14968. */
  14969. TransformNode.prototype.translate = function (axis, distance, space) {
  14970. var displacementVector = axis.scale(distance);
  14971. if (!space || space === BABYLON.Space.LOCAL) {
  14972. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14973. this.setPositionWithLocalVector(tempV3);
  14974. }
  14975. else {
  14976. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14977. }
  14978. return this;
  14979. };
  14980. /**
  14981. * Adds a rotation step to the mesh current rotation.
  14982. * x, y, z are Euler angles expressed in radians.
  14983. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14984. * This means this rotation is made in the mesh local space only.
  14985. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14986. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14987. * ```javascript
  14988. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14989. * ```
  14990. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14991. * 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.
  14992. * Returns the AbstractMesh.
  14993. */
  14994. TransformNode.prototype.addRotation = function (x, y, z) {
  14995. var rotationQuaternion;
  14996. if (this.rotationQuaternion) {
  14997. rotationQuaternion = this.rotationQuaternion;
  14998. }
  14999. else {
  15000. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15001. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15002. }
  15003. var accumulation = BABYLON.Tmp.Quaternion[0];
  15004. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15005. rotationQuaternion.multiplyInPlace(accumulation);
  15006. if (!this.rotationQuaternion) {
  15007. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15008. }
  15009. return this;
  15010. };
  15011. /**
  15012. * Computes the mesh World matrix and returns it.
  15013. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15014. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15015. * If the parameter `force`is set to `true`, the actual computation is done.
  15016. * Returns the mesh World Matrix.
  15017. */
  15018. TransformNode.prototype.computeWorldMatrix = function (force) {
  15019. if (this._isWorldMatrixFrozen) {
  15020. return this._worldMatrix;
  15021. }
  15022. if (!force && this.isSynchronized(true)) {
  15023. return this._worldMatrix;
  15024. }
  15025. this._cache.position.copyFrom(this.position);
  15026. this._cache.scaling.copyFrom(this.scaling);
  15027. this._cache.pivotMatrixUpdated = false;
  15028. this._cache.billboardMode = this.billboardMode;
  15029. this._currentRenderId = this.getScene().getRenderId();
  15030. this._isDirty = false;
  15031. // Scaling
  15032. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15033. // Rotation
  15034. //rotate, if quaternion is set and rotation was used
  15035. if (this.rotationQuaternion) {
  15036. var len = this.rotation.length();
  15037. if (len) {
  15038. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15039. this.rotation.copyFromFloats(0, 0, 0);
  15040. }
  15041. }
  15042. if (this.rotationQuaternion) {
  15043. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15044. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15045. }
  15046. else {
  15047. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15048. this._cache.rotation.copyFrom(this.rotation);
  15049. }
  15050. // Translation
  15051. var camera = this.getScene().activeCamera;
  15052. if (this.infiniteDistance && !this.parent && camera) {
  15053. var cameraWorldMatrix = camera.getWorldMatrix();
  15054. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15055. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15056. }
  15057. else {
  15058. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15059. }
  15060. // Composing transformations
  15061. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15062. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15063. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15064. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15065. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15066. // Need to decompose each rotation here
  15067. var currentPosition = BABYLON.Tmp.Vector3[3];
  15068. if (this.parent && this.parent.getWorldMatrix) {
  15069. if (this._transformToBoneReferal) {
  15070. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15071. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15072. }
  15073. else {
  15074. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15075. }
  15076. }
  15077. else {
  15078. currentPosition.copyFrom(this.position);
  15079. }
  15080. currentPosition.subtractInPlace(camera.globalPosition);
  15081. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15082. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15083. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15084. }
  15085. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15086. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15087. }
  15088. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15089. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15090. }
  15091. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15092. }
  15093. else {
  15094. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15095. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15096. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15097. }
  15098. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15099. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15100. }
  15101. // Local world
  15102. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15103. // Parent
  15104. if (this.parent && this.parent.getWorldMatrix) {
  15105. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15106. if (this._transformToBoneReferal) {
  15107. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15108. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15109. }
  15110. else {
  15111. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15112. }
  15113. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15114. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15115. this._worldMatrix.copyFrom(this._localWorld);
  15116. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15117. }
  15118. else {
  15119. if (this._transformToBoneReferal) {
  15120. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15121. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15122. }
  15123. else {
  15124. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15125. }
  15126. }
  15127. this._markSyncedWithParent();
  15128. }
  15129. else {
  15130. this._worldMatrix.copyFrom(this._localWorld);
  15131. }
  15132. // Post multiply inverse of pivotMatrix
  15133. if (this._postMultiplyPivotMatrix) {
  15134. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15135. }
  15136. // Normal matrix
  15137. if (this.scaling.isNonUniform) {
  15138. this._updateNonUniformScalingState(true);
  15139. }
  15140. else if (this.parent && this.parent._nonUniformScaling) {
  15141. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15142. }
  15143. else {
  15144. this._updateNonUniformScalingState(false);
  15145. }
  15146. this._afterComputeWorldMatrix();
  15147. // Absolute position
  15148. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15149. // Callbacks
  15150. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15151. if (!this._poseMatrix) {
  15152. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15153. }
  15154. // Cache the determinant
  15155. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15156. return this._worldMatrix;
  15157. };
  15158. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15159. };
  15160. /**
  15161. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15162. * @param func: callback function to add
  15163. *
  15164. * Returns the TransformNode.
  15165. */
  15166. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15167. this.onAfterWorldMatrixUpdateObservable.add(func);
  15168. return this;
  15169. };
  15170. /**
  15171. * Removes a registered callback function.
  15172. * Returns the TransformNode.
  15173. */
  15174. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15175. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15176. return this;
  15177. };
  15178. /**
  15179. * Clone the current transform node
  15180. * Returns the new transform node
  15181. * @param name Name of the new clone
  15182. * @param newParent New parent for the clone
  15183. * @param doNotCloneChildren Do not clone children hierarchy
  15184. */
  15185. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15186. var _this = this;
  15187. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15188. result.name = name;
  15189. result.id = name;
  15190. if (newParent) {
  15191. result.parent = newParent;
  15192. }
  15193. if (!doNotCloneChildren) {
  15194. // Children
  15195. var directDescendants = this.getDescendants(true);
  15196. for (var index = 0; index < directDescendants.length; index++) {
  15197. var child = directDescendants[index];
  15198. if (child.clone) {
  15199. child.clone(name + "." + child.name, result);
  15200. }
  15201. }
  15202. }
  15203. return result;
  15204. };
  15205. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15206. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15207. serializationObject.type = this.getClassName();
  15208. // Parent
  15209. if (this.parent) {
  15210. serializationObject.parentId = this.parent.id;
  15211. }
  15212. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15213. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15214. }
  15215. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15216. serializationObject.isEnabled = this.isEnabled();
  15217. // Parent
  15218. if (this.parent) {
  15219. serializationObject.parentId = this.parent.id;
  15220. }
  15221. return serializationObject;
  15222. };
  15223. // Statics
  15224. /**
  15225. * Returns a new TransformNode object parsed from the source provided.
  15226. * The parameter `parsedMesh` is the source.
  15227. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15228. */
  15229. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15230. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15231. if (BABYLON.Tags) {
  15232. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15233. }
  15234. if (parsedTransformNode.localMatrix) {
  15235. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15236. }
  15237. else if (parsedTransformNode.pivotMatrix) {
  15238. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15239. }
  15240. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15241. // Parent
  15242. if (parsedTransformNode.parentId) {
  15243. transformNode._waitingParentId = parsedTransformNode.parentId;
  15244. }
  15245. return transformNode;
  15246. };
  15247. /**
  15248. * Disposes the TransformNode.
  15249. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15250. * Returns nothing.
  15251. */
  15252. TransformNode.prototype.dispose = function (doNotRecurse) {
  15253. // Animations
  15254. this.getScene().stopAnimation(this);
  15255. // Remove from scene
  15256. this.getScene().removeTransformNode(this);
  15257. if (!doNotRecurse) {
  15258. // Children
  15259. var objects = this.getDescendants(true);
  15260. for (var index = 0; index < objects.length; index++) {
  15261. objects[index].dispose();
  15262. }
  15263. }
  15264. else {
  15265. var childMeshes = this.getChildMeshes(true);
  15266. for (index = 0; index < childMeshes.length; index++) {
  15267. var child = childMeshes[index];
  15268. child.parent = null;
  15269. child.computeWorldMatrix(true);
  15270. }
  15271. }
  15272. this.onAfterWorldMatrixUpdateObservable.clear();
  15273. _super.prototype.dispose.call(this);
  15274. };
  15275. // Statics
  15276. TransformNode.BILLBOARDMODE_NONE = 0;
  15277. TransformNode.BILLBOARDMODE_X = 1;
  15278. TransformNode.BILLBOARDMODE_Y = 2;
  15279. TransformNode.BILLBOARDMODE_Z = 4;
  15280. TransformNode.BILLBOARDMODE_ALL = 7;
  15281. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15282. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15283. __decorate([
  15284. BABYLON.serializeAsVector3()
  15285. ], TransformNode.prototype, "_rotation", void 0);
  15286. __decorate([
  15287. BABYLON.serializeAsQuaternion()
  15288. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15289. __decorate([
  15290. BABYLON.serializeAsVector3()
  15291. ], TransformNode.prototype, "_scaling", void 0);
  15292. __decorate([
  15293. BABYLON.serialize()
  15294. ], TransformNode.prototype, "billboardMode", void 0);
  15295. __decorate([
  15296. BABYLON.serialize()
  15297. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15298. __decorate([
  15299. BABYLON.serialize()
  15300. ], TransformNode.prototype, "infiniteDistance", void 0);
  15301. __decorate([
  15302. BABYLON.serializeAsVector3()
  15303. ], TransformNode.prototype, "position", void 0);
  15304. return TransformNode;
  15305. }(BABYLON.Node));
  15306. BABYLON.TransformNode = TransformNode;
  15307. })(BABYLON || (BABYLON = {}));
  15308. //# sourceMappingURL=babylon.transformNode.js.map
  15309. var BABYLON;
  15310. (function (BABYLON) {
  15311. var AbstractMesh = /** @class */ (function (_super) {
  15312. __extends(AbstractMesh, _super);
  15313. // Constructor
  15314. function AbstractMesh(name, scene) {
  15315. if (scene === void 0) { scene = null; }
  15316. var _this = _super.call(this, name, scene, false) || this;
  15317. _this._facetNb = 0; // facet number
  15318. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15319. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15320. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15321. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15322. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15323. _this._subDiv = {
  15324. max: 1,
  15325. X: 1,
  15326. Y: 1,
  15327. Z: 1
  15328. };
  15329. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15330. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15331. // Events
  15332. /**
  15333. * An event triggered when this mesh collides with another one
  15334. * @type {BABYLON.Observable}
  15335. */
  15336. _this.onCollideObservable = new BABYLON.Observable();
  15337. /**
  15338. * An event triggered when the collision's position changes
  15339. * @type {BABYLON.Observable}
  15340. */
  15341. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15342. /**
  15343. * An event triggered when material is changed
  15344. * @type {BABYLON.Observable}
  15345. */
  15346. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15347. // Properties
  15348. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15349. /**
  15350. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15351. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15352. * or
  15353. * 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.
  15354. * for more info check WebGl documentations
  15355. */
  15356. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15357. /**
  15358. * 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:
  15359. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15360. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15361. * 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.
  15362. */
  15363. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15364. /**
  15365. * 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.
  15366. * The default value is -1 which means don't break the query and wait till the result.
  15367. */
  15368. _this.occlusionRetryCount = -1;
  15369. _this._occlusionInternalRetryCounter = 0;
  15370. _this._isOccluded = false;
  15371. _this._isOcclusionQueryInProgress = false;
  15372. _this.visibility = 1.0;
  15373. _this.alphaIndex = Number.MAX_VALUE;
  15374. _this.isVisible = true;
  15375. _this.isPickable = true;
  15376. _this.showBoundingBox = false;
  15377. _this.showSubMeshesBoundingBox = false;
  15378. _this.isBlocker = false;
  15379. _this.enablePointerMoveEvents = false;
  15380. _this.renderingGroupId = 0;
  15381. _this._receiveShadows = false;
  15382. _this.renderOutline = false;
  15383. _this.outlineColor = BABYLON.Color3.Red();
  15384. _this.outlineWidth = 0.02;
  15385. _this.renderOverlay = false;
  15386. _this.overlayColor = BABYLON.Color3.Red();
  15387. _this.overlayAlpha = 0.5;
  15388. _this._hasVertexAlpha = false;
  15389. _this._useVertexColors = true;
  15390. _this._computeBonesUsingShaders = true;
  15391. _this._numBoneInfluencers = 4;
  15392. _this._applyFog = true;
  15393. _this.useOctreeForRenderingSelection = true;
  15394. _this.useOctreeForPicking = true;
  15395. _this.useOctreeForCollisions = true;
  15396. _this._layerMask = 0x0FFFFFFF;
  15397. /**
  15398. * True if the mesh must be rendered in any case.
  15399. */
  15400. _this.alwaysSelectAsActiveMesh = false;
  15401. /**
  15402. * This scene's action manager
  15403. * @type {BABYLON.ActionManager}
  15404. */
  15405. _this.actionManager = null;
  15406. // Physics
  15407. _this.physicsImpostor = null;
  15408. // Collisions
  15409. _this._checkCollisions = false;
  15410. _this._collisionMask = -1;
  15411. _this._collisionGroup = -1;
  15412. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15413. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15414. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15415. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15416. // Edges
  15417. _this.edgesWidth = 1;
  15418. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15419. // Cache
  15420. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15421. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15422. _this._isDisposed = false;
  15423. _this._renderId = 0;
  15424. _this._intersectionsInProgress = new Array();
  15425. _this._unIndexed = false;
  15426. _this._lightSources = new Array();
  15427. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15428. if (collidedMesh === void 0) { collidedMesh = null; }
  15429. //TODO move this to the collision coordinator!
  15430. if (_this.getScene().workerCollisions)
  15431. newPosition.multiplyInPlace(_this._collider._radius);
  15432. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15433. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15434. _this.position.addInPlace(_this._diffPositionForCollisions);
  15435. }
  15436. if (collidedMesh) {
  15437. _this.onCollideObservable.notifyObservers(collidedMesh);
  15438. }
  15439. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15440. };
  15441. _this.getScene().addMesh(_this);
  15442. _this._resyncLightSources();
  15443. return _this;
  15444. }
  15445. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15446. get: function () {
  15447. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15448. },
  15449. enumerable: true,
  15450. configurable: true
  15451. });
  15452. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15453. get: function () {
  15454. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15455. },
  15456. enumerable: true,
  15457. configurable: true
  15458. });
  15459. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15460. get: function () {
  15461. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15462. },
  15463. enumerable: true,
  15464. configurable: true
  15465. });
  15466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15467. get: function () {
  15468. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15469. },
  15470. enumerable: true,
  15471. configurable: true
  15472. });
  15473. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15474. get: function () {
  15475. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15476. },
  15477. enumerable: true,
  15478. configurable: true
  15479. });
  15480. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15481. /**
  15482. * Read-only : the number of facets in the mesh
  15483. */
  15484. get: function () {
  15485. return this._facetNb;
  15486. },
  15487. enumerable: true,
  15488. configurable: true
  15489. });
  15490. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15491. /**
  15492. * The number (integer) of subdivisions per axis in the partioning space
  15493. */
  15494. get: function () {
  15495. return this._partitioningSubdivisions;
  15496. },
  15497. set: function (nb) {
  15498. this._partitioningSubdivisions = nb;
  15499. },
  15500. enumerable: true,
  15501. configurable: true
  15502. });
  15503. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15504. /**
  15505. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15506. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15507. */
  15508. get: function () {
  15509. return this._partitioningBBoxRatio;
  15510. },
  15511. set: function (ratio) {
  15512. this._partitioningBBoxRatio = ratio;
  15513. },
  15514. enumerable: true,
  15515. configurable: true
  15516. });
  15517. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15518. /**
  15519. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15520. * Works only for updatable meshes.
  15521. * Doesn't work with multi-materials.
  15522. */
  15523. get: function () {
  15524. return this._facetDepthSort;
  15525. },
  15526. set: function (sort) {
  15527. this._facetDepthSort = sort;
  15528. },
  15529. enumerable: true,
  15530. configurable: true
  15531. });
  15532. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15533. /**
  15534. * The location (Vector3) where the facet depth sort must be computed from.
  15535. * By default, the active camera position.
  15536. * Used only when facet depth sort is enabled.
  15537. */
  15538. get: function () {
  15539. return this._facetDepthSortFrom;
  15540. },
  15541. set: function (location) {
  15542. this._facetDepthSortFrom = location;
  15543. },
  15544. enumerable: true,
  15545. configurable: true
  15546. });
  15547. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15548. /**
  15549. * Read-only boolean : is the feature facetData enabled ?
  15550. */
  15551. get: function () {
  15552. return this._facetDataEnabled;
  15553. },
  15554. enumerable: true,
  15555. configurable: true
  15556. });
  15557. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15558. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15559. return false;
  15560. }
  15561. this._markSubMeshesAsMiscDirty();
  15562. return true;
  15563. };
  15564. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15565. set: function (callback) {
  15566. if (this._onCollideObserver) {
  15567. this.onCollideObservable.remove(this._onCollideObserver);
  15568. }
  15569. this._onCollideObserver = this.onCollideObservable.add(callback);
  15570. },
  15571. enumerable: true,
  15572. configurable: true
  15573. });
  15574. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15575. set: function (callback) {
  15576. if (this._onCollisionPositionChangeObserver) {
  15577. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15578. }
  15579. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15580. },
  15581. enumerable: true,
  15582. configurable: true
  15583. });
  15584. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15585. /**
  15586. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  15587. */
  15588. get: function () {
  15589. return this._isOccluded;
  15590. },
  15591. set: function (value) {
  15592. this._isOccluded = value;
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15598. /**
  15599. * Flag to check the progress status of the query
  15600. */
  15601. get: function () {
  15602. return this._isOcclusionQueryInProgress;
  15603. },
  15604. enumerable: true,
  15605. configurable: true
  15606. });
  15607. Object.defineProperty(AbstractMesh.prototype, "material", {
  15608. get: function () {
  15609. return this._material;
  15610. },
  15611. set: function (value) {
  15612. if (this._material === value) {
  15613. return;
  15614. }
  15615. this._material = value;
  15616. if (this.onMaterialChangedObservable.hasObservers) {
  15617. this.onMaterialChangedObservable.notifyObservers(this);
  15618. }
  15619. if (!this.subMeshes) {
  15620. return;
  15621. }
  15622. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15623. var subMesh = _a[_i];
  15624. subMesh.setEffect(null);
  15625. }
  15626. },
  15627. enumerable: true,
  15628. configurable: true
  15629. });
  15630. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15631. get: function () {
  15632. return this._receiveShadows;
  15633. },
  15634. set: function (value) {
  15635. if (this._receiveShadows === value) {
  15636. return;
  15637. }
  15638. this._receiveShadows = value;
  15639. this._markSubMeshesAsLightDirty();
  15640. },
  15641. enumerable: true,
  15642. configurable: true
  15643. });
  15644. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15645. get: function () {
  15646. return this._hasVertexAlpha;
  15647. },
  15648. set: function (value) {
  15649. if (this._hasVertexAlpha === value) {
  15650. return;
  15651. }
  15652. this._hasVertexAlpha = value;
  15653. this._markSubMeshesAsAttributesDirty();
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15659. get: function () {
  15660. return this._useVertexColors;
  15661. },
  15662. set: function (value) {
  15663. if (this._useVertexColors === value) {
  15664. return;
  15665. }
  15666. this._useVertexColors = value;
  15667. this._markSubMeshesAsAttributesDirty();
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15673. get: function () {
  15674. return this._computeBonesUsingShaders;
  15675. },
  15676. set: function (value) {
  15677. if (this._computeBonesUsingShaders === value) {
  15678. return;
  15679. }
  15680. this._computeBonesUsingShaders = value;
  15681. this._markSubMeshesAsAttributesDirty();
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15687. get: function () {
  15688. return this._numBoneInfluencers;
  15689. },
  15690. set: function (value) {
  15691. if (this._numBoneInfluencers === value) {
  15692. return;
  15693. }
  15694. this._numBoneInfluencers = value;
  15695. this._markSubMeshesAsAttributesDirty();
  15696. },
  15697. enumerable: true,
  15698. configurable: true
  15699. });
  15700. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15701. get: function () {
  15702. return this._applyFog;
  15703. },
  15704. set: function (value) {
  15705. if (this._applyFog === value) {
  15706. return;
  15707. }
  15708. this._applyFog = value;
  15709. this._markSubMeshesAsMiscDirty();
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15715. get: function () {
  15716. return this._layerMask;
  15717. },
  15718. set: function (value) {
  15719. if (value === this._layerMask) {
  15720. return;
  15721. }
  15722. this._layerMask = value;
  15723. this._resyncLightSources();
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15729. get: function () {
  15730. return this._collisionMask;
  15731. },
  15732. set: function (mask) {
  15733. this._collisionMask = !isNaN(mask) ? mask : -1;
  15734. },
  15735. enumerable: true,
  15736. configurable: true
  15737. });
  15738. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15739. get: function () {
  15740. return this._collisionGroup;
  15741. },
  15742. set: function (mask) {
  15743. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15749. get: function () {
  15750. return null;
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15756. get: function () {
  15757. return this._skeleton;
  15758. },
  15759. set: function (value) {
  15760. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15761. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15762. }
  15763. if (value && value.needInitialSkinMatrix) {
  15764. value._registerMeshWithPoseMatrix(this);
  15765. }
  15766. this._skeleton = value;
  15767. if (!this._skeleton) {
  15768. this._bonesTransformMatrices = null;
  15769. }
  15770. this._markSubMeshesAsAttributesDirty();
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. /**
  15776. * Boolean : true if the mesh has been disposed.
  15777. */
  15778. AbstractMesh.prototype.isDisposed = function () {
  15779. return this._isDisposed;
  15780. };
  15781. /**
  15782. * Returns the string "AbstractMesh"
  15783. */
  15784. AbstractMesh.prototype.getClassName = function () {
  15785. return "AbstractMesh";
  15786. };
  15787. /**
  15788. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15789. */
  15790. AbstractMesh.prototype.toString = function (fullDetails) {
  15791. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15792. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15793. if (this._skeleton) {
  15794. ret += ", skeleton: " + this._skeleton.name;
  15795. }
  15796. if (fullDetails) {
  15797. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15798. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15799. }
  15800. return ret;
  15801. };
  15802. AbstractMesh.prototype._rebuild = function () {
  15803. if (this._occlusionQuery) {
  15804. this._occlusionQuery = null;
  15805. }
  15806. if (this._edgesRenderer) {
  15807. this._edgesRenderer._rebuild();
  15808. }
  15809. if (!this.subMeshes) {
  15810. return;
  15811. }
  15812. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15813. var subMesh = _a[_i];
  15814. subMesh._rebuild();
  15815. }
  15816. };
  15817. AbstractMesh.prototype._resyncLightSources = function () {
  15818. this._lightSources.length = 0;
  15819. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15820. var light = _a[_i];
  15821. if (!light.isEnabled()) {
  15822. continue;
  15823. }
  15824. if (light.canAffectMesh(this)) {
  15825. this._lightSources.push(light);
  15826. }
  15827. }
  15828. this._markSubMeshesAsLightDirty();
  15829. };
  15830. AbstractMesh.prototype._resyncLighSource = function (light) {
  15831. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15832. var index = this._lightSources.indexOf(light);
  15833. if (index === -1) {
  15834. if (!isIn) {
  15835. return;
  15836. }
  15837. this._lightSources.push(light);
  15838. }
  15839. else {
  15840. if (isIn) {
  15841. return;
  15842. }
  15843. this._lightSources.splice(index, 1);
  15844. }
  15845. this._markSubMeshesAsLightDirty();
  15846. };
  15847. AbstractMesh.prototype._removeLightSource = function (light) {
  15848. var index = this._lightSources.indexOf(light);
  15849. if (index === -1) {
  15850. return;
  15851. }
  15852. this._lightSources.splice(index, 1);
  15853. this._markSubMeshesAsLightDirty();
  15854. };
  15855. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15856. if (!this.subMeshes) {
  15857. return;
  15858. }
  15859. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15860. var subMesh = _a[_i];
  15861. if (subMesh._materialDefines) {
  15862. func(subMesh._materialDefines);
  15863. }
  15864. }
  15865. };
  15866. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15867. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15868. };
  15869. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15870. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15871. };
  15872. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15873. if (!this.subMeshes) {
  15874. return;
  15875. }
  15876. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15877. var subMesh = _a[_i];
  15878. var material = subMesh.getMaterial();
  15879. if (material) {
  15880. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15881. }
  15882. }
  15883. };
  15884. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15885. /**
  15886. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15887. * Default : (1.0, 1.0, 1.0)
  15888. */
  15889. get: function () {
  15890. return this._scaling;
  15891. },
  15892. /**
  15893. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15894. * Default : (1.0, 1.0, 1.0)
  15895. */
  15896. set: function (newScaling) {
  15897. this._scaling = newScaling;
  15898. if (this.physicsImpostor) {
  15899. this.physicsImpostor.forceUpdate();
  15900. }
  15901. },
  15902. enumerable: true,
  15903. configurable: true
  15904. });
  15905. // Methods
  15906. /**
  15907. * Disables the mesh edger rendering mode.
  15908. * Returns the AbstractMesh.
  15909. */
  15910. AbstractMesh.prototype.disableEdgesRendering = function () {
  15911. if (this._edgesRenderer) {
  15912. this._edgesRenderer.dispose();
  15913. this._edgesRenderer = null;
  15914. }
  15915. return this;
  15916. };
  15917. /**
  15918. * Enables the edge rendering mode on the mesh.
  15919. * This mode makes the mesh edges visible.
  15920. * Returns the AbstractMesh.
  15921. */
  15922. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15923. if (epsilon === void 0) { epsilon = 0.95; }
  15924. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15925. this.disableEdgesRendering();
  15926. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15927. return this;
  15928. };
  15929. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15930. /**
  15931. * Returns true if the mesh is blocked. Used by the class Mesh.
  15932. * Returns the boolean `false` by default.
  15933. */
  15934. get: function () {
  15935. return false;
  15936. },
  15937. enumerable: true,
  15938. configurable: true
  15939. });
  15940. /**
  15941. * Returns the mesh itself by default, used by the class Mesh.
  15942. * Returned type : AbstractMesh
  15943. */
  15944. AbstractMesh.prototype.getLOD = function (camera) {
  15945. return this;
  15946. };
  15947. /**
  15948. * Returns 0 by default, used by the class Mesh.
  15949. * Returns an integer.
  15950. */
  15951. AbstractMesh.prototype.getTotalVertices = function () {
  15952. return 0;
  15953. };
  15954. /**
  15955. * Returns null by default, used by the class Mesh.
  15956. * Returned type : integer array
  15957. */
  15958. AbstractMesh.prototype.getIndices = function () {
  15959. return null;
  15960. };
  15961. /**
  15962. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15963. * Returned type : float array or Float32Array
  15964. */
  15965. AbstractMesh.prototype.getVerticesData = function (kind) {
  15966. return null;
  15967. };
  15968. /**
  15969. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15970. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15971. * The `data` are either a numeric array either a Float32Array.
  15972. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15973. * 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).
  15974. * Note that a new underlying VertexBuffer object is created each call.
  15975. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15976. *
  15977. * Possible `kind` values :
  15978. * - BABYLON.VertexBuffer.PositionKind
  15979. * - BABYLON.VertexBuffer.UVKind
  15980. * - BABYLON.VertexBuffer.UV2Kind
  15981. * - BABYLON.VertexBuffer.UV3Kind
  15982. * - BABYLON.VertexBuffer.UV4Kind
  15983. * - BABYLON.VertexBuffer.UV5Kind
  15984. * - BABYLON.VertexBuffer.UV6Kind
  15985. * - BABYLON.VertexBuffer.ColorKind
  15986. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15987. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15988. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15989. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15990. *
  15991. * Returns the Mesh.
  15992. */
  15993. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15994. return this;
  15995. };
  15996. /**
  15997. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15998. * If the mesh has no geometry, it is simply returned as it is.
  15999. * The `data` are either a numeric array either a Float32Array.
  16000. * No new underlying VertexBuffer object is created.
  16001. * 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.
  16002. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16003. *
  16004. * Possible `kind` values :
  16005. * - BABYLON.VertexBuffer.PositionKind
  16006. * - BABYLON.VertexBuffer.UVKind
  16007. * - BABYLON.VertexBuffer.UV2Kind
  16008. * - BABYLON.VertexBuffer.UV3Kind
  16009. * - BABYLON.VertexBuffer.UV4Kind
  16010. * - BABYLON.VertexBuffer.UV5Kind
  16011. * - BABYLON.VertexBuffer.UV6Kind
  16012. * - BABYLON.VertexBuffer.ColorKind
  16013. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16014. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16015. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16016. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16017. *
  16018. * Returns the Mesh.
  16019. */
  16020. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16021. return this;
  16022. };
  16023. /**
  16024. * Sets the mesh indices.
  16025. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16026. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16027. * This method creates a new index buffer each call.
  16028. * Returns the Mesh.
  16029. */
  16030. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16031. return this;
  16032. };
  16033. /** Returns false by default, used by the class Mesh.
  16034. * Returns a boolean
  16035. */
  16036. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16037. return false;
  16038. };
  16039. /**
  16040. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16041. * Returns a BoundingInfo
  16042. */
  16043. AbstractMesh.prototype.getBoundingInfo = function () {
  16044. if (this._masterMesh) {
  16045. return this._masterMesh.getBoundingInfo();
  16046. }
  16047. if (!this._boundingInfo) {
  16048. // this._boundingInfo is being created here
  16049. this._updateBoundingInfo();
  16050. }
  16051. // cannot be null.
  16052. return this._boundingInfo;
  16053. };
  16054. /**
  16055. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16056. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16057. */
  16058. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16059. if (includeDescendants === void 0) { includeDescendants = true; }
  16060. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16061. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16062. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16063. if (maxDimension === 0) {
  16064. return this;
  16065. }
  16066. var scale = 1 / maxDimension;
  16067. this.scaling.scaleInPlace(scale);
  16068. return this;
  16069. };
  16070. /**
  16071. * Sets a mesh new object BoundingInfo.
  16072. * Returns the AbstractMesh.
  16073. */
  16074. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16075. this._boundingInfo = boundingInfo;
  16076. return this;
  16077. };
  16078. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16079. get: function () {
  16080. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. AbstractMesh.prototype._preActivate = function () {
  16086. };
  16087. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16088. };
  16089. AbstractMesh.prototype._activate = function (renderId) {
  16090. this._renderId = renderId;
  16091. };
  16092. /**
  16093. * Returns the latest update of the World matrix
  16094. * Returns a Matrix.
  16095. */
  16096. AbstractMesh.prototype.getWorldMatrix = function () {
  16097. if (this._masterMesh) {
  16098. return this._masterMesh.getWorldMatrix();
  16099. }
  16100. return _super.prototype.getWorldMatrix.call(this);
  16101. };
  16102. /**
  16103. * Returns the latest update of the World matrix determinant.
  16104. */
  16105. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16106. if (this._masterMesh) {
  16107. return this._masterMesh._getWorldMatrixDeterminant();
  16108. }
  16109. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16110. };
  16111. // ================================== Point of View Movement =================================
  16112. /**
  16113. * Perform relative position change from the point of view of behind the front of the mesh.
  16114. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16115. * Supports definition of mesh facing forward or backward.
  16116. * @param {number} amountRight
  16117. * @param {number} amountUp
  16118. * @param {number} amountForward
  16119. *
  16120. * Returns the AbstractMesh.
  16121. */
  16122. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16123. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16124. return this;
  16125. };
  16126. /**
  16127. * Calculate relative position change from the point of view of behind the front of the mesh.
  16128. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16129. * Supports definition of mesh facing forward or backward.
  16130. * @param {number} amountRight
  16131. * @param {number} amountUp
  16132. * @param {number} amountForward
  16133. *
  16134. * Returns a new Vector3.
  16135. */
  16136. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16137. var rotMatrix = new BABYLON.Matrix();
  16138. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16139. rotQuaternion.toRotationMatrix(rotMatrix);
  16140. var translationDelta = BABYLON.Vector3.Zero();
  16141. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16142. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16143. return translationDelta;
  16144. };
  16145. // ================================== Point of View Rotation =================================
  16146. /**
  16147. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16148. * Supports definition of mesh facing forward or backward.
  16149. * @param {number} flipBack
  16150. * @param {number} twirlClockwise
  16151. * @param {number} tiltRight
  16152. *
  16153. * Returns the AbstractMesh.
  16154. */
  16155. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16156. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16157. return this;
  16158. };
  16159. /**
  16160. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16161. * Supports definition of mesh facing forward or backward.
  16162. * @param {number} flipBack
  16163. * @param {number} twirlClockwise
  16164. * @param {number} tiltRight
  16165. *
  16166. * Returns a new Vector3.
  16167. */
  16168. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16169. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16170. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16171. };
  16172. /**
  16173. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16174. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16175. */
  16176. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16177. if (includeDescendants === void 0) { includeDescendants = true; }
  16178. this.computeWorldMatrix(true);
  16179. var min;
  16180. var max;
  16181. var boundingInfo = this.getBoundingInfo();
  16182. if (!this.subMeshes) {
  16183. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16184. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16185. }
  16186. else {
  16187. min = boundingInfo.boundingBox.minimumWorld;
  16188. max = boundingInfo.boundingBox.maximumWorld;
  16189. }
  16190. if (includeDescendants) {
  16191. var descendants = this.getDescendants(false);
  16192. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16193. var descendant = descendants_1[_i];
  16194. var childMesh = descendant;
  16195. childMesh.computeWorldMatrix(true);
  16196. //make sure we have the needed params to get mix and max
  16197. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16198. continue;
  16199. }
  16200. var childBoundingInfo = childMesh.getBoundingInfo();
  16201. var boundingBox = childBoundingInfo.boundingBox;
  16202. var minBox = boundingBox.minimumWorld;
  16203. var maxBox = boundingBox.maximumWorld;
  16204. BABYLON.Tools.CheckExtends(minBox, min, max);
  16205. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16206. }
  16207. }
  16208. return {
  16209. min: min,
  16210. max: max
  16211. };
  16212. };
  16213. /**
  16214. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16215. * Returns the AbstractMesh.
  16216. */
  16217. AbstractMesh.prototype._updateBoundingInfo = function () {
  16218. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16219. this._boundingInfo.update(this.worldMatrixFromCache);
  16220. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16221. return this;
  16222. };
  16223. /**
  16224. * Update a mesh's children BoundingInfo objects only.
  16225. * Returns the AbstractMesh.
  16226. */
  16227. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16228. if (!this.subMeshes) {
  16229. return this;
  16230. }
  16231. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16232. var subMesh = this.subMeshes[subIndex];
  16233. if (!subMesh.IsGlobal) {
  16234. subMesh.updateBoundingInfo(matrix);
  16235. }
  16236. }
  16237. return this;
  16238. };
  16239. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16240. // Bounding info
  16241. this._updateBoundingInfo();
  16242. };
  16243. /**
  16244. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16245. * A mesh is in the frustum if its bounding box intersects the frustum.
  16246. * Boolean returned.
  16247. */
  16248. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16249. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16250. };
  16251. /**
  16252. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16253. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16254. * Boolean returned.
  16255. */
  16256. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16257. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16258. ;
  16259. };
  16260. /**
  16261. * True if the mesh intersects another mesh or a SolidParticle object.
  16262. * 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)
  16263. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16264. * Returns a boolean.
  16265. */
  16266. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16267. if (precise === void 0) { precise = false; }
  16268. if (!this._boundingInfo || !mesh._boundingInfo) {
  16269. return false;
  16270. }
  16271. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16272. return true;
  16273. }
  16274. if (includeDescendants) {
  16275. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16276. var child = _a[_i];
  16277. if (child.intersectsMesh(mesh, precise, true)) {
  16278. return true;
  16279. }
  16280. }
  16281. }
  16282. return false;
  16283. };
  16284. /**
  16285. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16286. * Returns a boolean.
  16287. */
  16288. AbstractMesh.prototype.intersectsPoint = function (point) {
  16289. if (!this._boundingInfo) {
  16290. return false;
  16291. }
  16292. return this._boundingInfo.intersectsPoint(point);
  16293. };
  16294. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16295. return this.physicsImpostor;
  16296. };
  16297. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16298. if (camera === void 0) { camera = null; }
  16299. if (!camera) {
  16300. camera = this.getScene().activeCamera;
  16301. }
  16302. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16303. };
  16304. /**
  16305. * Returns the distance from the mesh to the active camera.
  16306. * Returns a float.
  16307. */
  16308. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16309. if (camera === void 0) { camera = null; }
  16310. if (!camera) {
  16311. camera = this.getScene().activeCamera;
  16312. }
  16313. return this.absolutePosition.subtract(camera.position).length();
  16314. };
  16315. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16316. if (!this.physicsImpostor) {
  16317. return this;
  16318. }
  16319. this.physicsImpostor.applyImpulse(force, contactPoint);
  16320. return this;
  16321. };
  16322. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16323. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16324. return this;
  16325. }
  16326. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16327. mainPivot: pivot1,
  16328. connectedPivot: pivot2,
  16329. nativeParams: options
  16330. });
  16331. return this;
  16332. };
  16333. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16334. // Collisions
  16335. /**
  16336. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16337. * Default `false`.
  16338. */
  16339. get: function () {
  16340. return this._checkCollisions;
  16341. },
  16342. set: function (collisionEnabled) {
  16343. this._checkCollisions = collisionEnabled;
  16344. if (this.getScene().workerCollisions) {
  16345. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16346. }
  16347. },
  16348. enumerable: true,
  16349. configurable: true
  16350. });
  16351. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16352. /**
  16353. * Gets Collider object used to compute collisions (not physics)
  16354. */
  16355. get: function () {
  16356. return this._collider;
  16357. },
  16358. enumerable: true,
  16359. configurable: true
  16360. });
  16361. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16362. var globalPosition = this.getAbsolutePosition();
  16363. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16364. if (!this._collider) {
  16365. this._collider = new BABYLON.Collider();
  16366. }
  16367. this._collider._radius = this.ellipsoid;
  16368. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16369. return this;
  16370. };
  16371. // Submeshes octree
  16372. /**
  16373. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16374. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16375. * Returns an Octree of submeshes.
  16376. */
  16377. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16378. if (maxCapacity === void 0) { maxCapacity = 64; }
  16379. if (maxDepth === void 0) { maxDepth = 2; }
  16380. if (!this._submeshesOctree) {
  16381. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16382. }
  16383. this.computeWorldMatrix(true);
  16384. var boundingInfo = this.getBoundingInfo();
  16385. // Update octree
  16386. var bbox = boundingInfo.boundingBox;
  16387. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16388. return this._submeshesOctree;
  16389. };
  16390. // Collisions
  16391. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16392. this._generatePointsArray();
  16393. if (!this._positions) {
  16394. return this;
  16395. }
  16396. // Transformation
  16397. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16398. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16399. subMesh._lastColliderWorldVertices = [];
  16400. subMesh._trianglePlanes = [];
  16401. var start = subMesh.verticesStart;
  16402. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16403. for (var i = start; i < end; i++) {
  16404. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16405. }
  16406. }
  16407. // Collide
  16408. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16409. if (collider.collisionFound) {
  16410. collider.collidedMesh = this;
  16411. }
  16412. return this;
  16413. };
  16414. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16415. var subMeshes;
  16416. var len;
  16417. // Octrees
  16418. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16419. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16420. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16421. len = intersections.length;
  16422. subMeshes = intersections.data;
  16423. }
  16424. else {
  16425. subMeshes = this.subMeshes;
  16426. len = subMeshes.length;
  16427. }
  16428. for (var index = 0; index < len; index++) {
  16429. var subMesh = subMeshes[index];
  16430. // Bounding test
  16431. if (len > 1 && !subMesh._checkCollision(collider))
  16432. continue;
  16433. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16434. }
  16435. return this;
  16436. };
  16437. AbstractMesh.prototype._checkCollision = function (collider) {
  16438. // Bounding box test
  16439. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16440. return this;
  16441. // Transformation matrix
  16442. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16443. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16444. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16445. return this;
  16446. };
  16447. // Picking
  16448. AbstractMesh.prototype._generatePointsArray = function () {
  16449. return false;
  16450. };
  16451. /**
  16452. * Checks if the passed Ray intersects with the mesh.
  16453. * Returns an object PickingInfo.
  16454. */
  16455. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16456. var pickingInfo = new BABYLON.PickingInfo();
  16457. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16458. return pickingInfo;
  16459. }
  16460. if (!this._generatePointsArray()) {
  16461. return pickingInfo;
  16462. }
  16463. var intersectInfo = null;
  16464. // Octrees
  16465. var subMeshes;
  16466. var len;
  16467. if (this._submeshesOctree && this.useOctreeForPicking) {
  16468. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16469. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16470. len = intersections.length;
  16471. subMeshes = intersections.data;
  16472. }
  16473. else {
  16474. subMeshes = this.subMeshes;
  16475. len = subMeshes.length;
  16476. }
  16477. for (var index = 0; index < len; index++) {
  16478. var subMesh = subMeshes[index];
  16479. // Bounding test
  16480. if (len > 1 && !subMesh.canIntersects(ray))
  16481. continue;
  16482. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16483. if (currentIntersectInfo) {
  16484. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16485. intersectInfo = currentIntersectInfo;
  16486. intersectInfo.subMeshId = index;
  16487. if (fastCheck) {
  16488. break;
  16489. }
  16490. }
  16491. }
  16492. }
  16493. if (intersectInfo) {
  16494. // Get picked point
  16495. var world = this.getWorldMatrix();
  16496. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16497. var direction = ray.direction.clone();
  16498. direction = direction.scale(intersectInfo.distance);
  16499. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16500. var pickedPoint = worldOrigin.add(worldDirection);
  16501. // Return result
  16502. pickingInfo.hit = true;
  16503. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16504. pickingInfo.pickedPoint = pickedPoint;
  16505. pickingInfo.pickedMesh = this;
  16506. pickingInfo.bu = intersectInfo.bu || 0;
  16507. pickingInfo.bv = intersectInfo.bv || 0;
  16508. pickingInfo.faceId = intersectInfo.faceId;
  16509. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16510. return pickingInfo;
  16511. }
  16512. return pickingInfo;
  16513. };
  16514. /**
  16515. * Clones the mesh, used by the class Mesh.
  16516. * Just returns `null` for an AbstractMesh.
  16517. */
  16518. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16519. return null;
  16520. };
  16521. /**
  16522. * Disposes all the mesh submeshes.
  16523. * Returns the AbstractMesh.
  16524. */
  16525. AbstractMesh.prototype.releaseSubMeshes = function () {
  16526. if (this.subMeshes) {
  16527. while (this.subMeshes.length) {
  16528. this.subMeshes[0].dispose();
  16529. }
  16530. }
  16531. else {
  16532. this.subMeshes = new Array();
  16533. }
  16534. return this;
  16535. };
  16536. /**
  16537. * Disposes the AbstractMesh.
  16538. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16539. * Returns nothing.
  16540. */
  16541. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16542. var _this = this;
  16543. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16544. var index;
  16545. // Action manager
  16546. if (this.actionManager !== undefined && this.actionManager !== null) {
  16547. this.actionManager.dispose();
  16548. this.actionManager = null;
  16549. }
  16550. // Skeleton
  16551. this.skeleton = null;
  16552. // Physics
  16553. if (this.physicsImpostor) {
  16554. this.physicsImpostor.dispose();
  16555. }
  16556. // Intersections in progress
  16557. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16558. var other = this._intersectionsInProgress[index];
  16559. var pos = other._intersectionsInProgress.indexOf(this);
  16560. other._intersectionsInProgress.splice(pos, 1);
  16561. }
  16562. this._intersectionsInProgress = [];
  16563. // Lights
  16564. var lights = this.getScene().lights;
  16565. lights.forEach(function (light) {
  16566. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16567. if (meshIndex !== -1) {
  16568. light.includedOnlyMeshes.splice(meshIndex, 1);
  16569. }
  16570. meshIndex = light.excludedMeshes.indexOf(_this);
  16571. if (meshIndex !== -1) {
  16572. light.excludedMeshes.splice(meshIndex, 1);
  16573. }
  16574. // Shadow generators
  16575. var generator = light.getShadowGenerator();
  16576. if (generator) {
  16577. var shadowMap = generator.getShadowMap();
  16578. if (shadowMap && shadowMap.renderList) {
  16579. meshIndex = shadowMap.renderList.indexOf(_this);
  16580. if (meshIndex !== -1) {
  16581. shadowMap.renderList.splice(meshIndex, 1);
  16582. }
  16583. }
  16584. }
  16585. });
  16586. // Edges
  16587. if (this._edgesRenderer) {
  16588. this._edgesRenderer.dispose();
  16589. this._edgesRenderer = null;
  16590. }
  16591. // SubMeshes
  16592. if (this.getClassName() !== "InstancedMesh") {
  16593. this.releaseSubMeshes();
  16594. }
  16595. // Octree
  16596. var sceneOctree = this.getScene().selectionOctree;
  16597. if (sceneOctree !== undefined && sceneOctree !== null) {
  16598. var index = sceneOctree.dynamicContent.indexOf(this);
  16599. if (index !== -1) {
  16600. sceneOctree.dynamicContent.splice(index, 1);
  16601. }
  16602. }
  16603. // Query
  16604. var engine = this.getScene().getEngine();
  16605. if (this._occlusionQuery) {
  16606. this._isOcclusionQueryInProgress = false;
  16607. engine.deleteQuery(this._occlusionQuery);
  16608. this._occlusionQuery = null;
  16609. }
  16610. // Engine
  16611. engine.wipeCaches();
  16612. // Remove from scene
  16613. this.getScene().removeMesh(this);
  16614. if (disposeMaterialAndTextures) {
  16615. if (this.material) {
  16616. this.material.dispose(false, true);
  16617. }
  16618. }
  16619. if (!doNotRecurse) {
  16620. // Particles
  16621. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16622. if (this.getScene().particleSystems[index].emitter === this) {
  16623. this.getScene().particleSystems[index].dispose();
  16624. index--;
  16625. }
  16626. }
  16627. }
  16628. // facet data
  16629. if (this._facetDataEnabled) {
  16630. this.disableFacetData();
  16631. }
  16632. this.onAfterWorldMatrixUpdateObservable.clear();
  16633. this.onCollideObservable.clear();
  16634. this.onCollisionPositionChangeObservable.clear();
  16635. this._isDisposed = true;
  16636. _super.prototype.dispose.call(this, doNotRecurse);
  16637. };
  16638. /**
  16639. * Adds the passed mesh as a child to the current mesh.
  16640. * Returns the AbstractMesh.
  16641. */
  16642. AbstractMesh.prototype.addChild = function (mesh) {
  16643. mesh.setParent(this);
  16644. return this;
  16645. };
  16646. /**
  16647. * Removes the passed mesh from the current mesh children list.
  16648. * Returns the AbstractMesh.
  16649. */
  16650. AbstractMesh.prototype.removeChild = function (mesh) {
  16651. mesh.setParent(null);
  16652. return this;
  16653. };
  16654. // Facet data
  16655. /**
  16656. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16657. * Returns the AbstractMesh.
  16658. */
  16659. AbstractMesh.prototype._initFacetData = function () {
  16660. if (!this._facetNormals) {
  16661. this._facetNormals = new Array();
  16662. }
  16663. if (!this._facetPositions) {
  16664. this._facetPositions = new Array();
  16665. }
  16666. if (!this._facetPartitioning) {
  16667. this._facetPartitioning = new Array();
  16668. }
  16669. this._facetNb = (this.getIndices().length / 3) | 0;
  16670. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16671. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16672. for (var f = 0; f < this._facetNb; f++) {
  16673. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16674. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16675. }
  16676. this._facetDataEnabled = true;
  16677. return this;
  16678. };
  16679. /**
  16680. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16681. * This method can be called within the render loop.
  16682. * 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.
  16683. * Returns the AbstractMesh.
  16684. */
  16685. AbstractMesh.prototype.updateFacetData = function () {
  16686. if (!this._facetDataEnabled) {
  16687. this._initFacetData();
  16688. }
  16689. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16690. var indices = this.getIndices();
  16691. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16692. var bInfo = this.getBoundingInfo();
  16693. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16694. // init arrays, matrix and sort function on first call
  16695. this._facetDepthSortEnabled = true;
  16696. if (indices instanceof Uint16Array) {
  16697. this._depthSortedIndices = new Uint16Array(indices);
  16698. }
  16699. else if (indices instanceof Uint32Array) {
  16700. this._depthSortedIndices = new Uint32Array(indices);
  16701. }
  16702. else {
  16703. var needs32bits = false;
  16704. for (var i = 0; i < indices.length; i++) {
  16705. if (indices[i] > 65535) {
  16706. needs32bits = true;
  16707. break;
  16708. }
  16709. }
  16710. if (needs32bits) {
  16711. this._depthSortedIndices = new Uint32Array(indices);
  16712. }
  16713. else {
  16714. this._depthSortedIndices = new Uint16Array(indices);
  16715. }
  16716. }
  16717. this._facetDepthSortFunction = function (f1, f2) {
  16718. return (f2.sqDistance - f1.sqDistance);
  16719. };
  16720. if (!this._facetDepthSortFrom) {
  16721. var camera = this.getScene().activeCamera;
  16722. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16723. }
  16724. this._depthSortedFacets = [];
  16725. for (var f = 0; f < this._facetNb; f++) {
  16726. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16727. this._depthSortedFacets.push(depthSortedFacet);
  16728. }
  16729. this._invertedMatrix = BABYLON.Matrix.Identity();
  16730. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16731. }
  16732. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16733. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16734. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16735. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16736. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16737. this._subDiv.max = this._partitioningSubdivisions;
  16738. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16739. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16740. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16741. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16742. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16743. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16744. // set the parameters for ComputeNormals()
  16745. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16746. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16747. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16748. this._facetParameters.bInfo = bInfo;
  16749. this._facetParameters.bbSize = this._bbSize;
  16750. this._facetParameters.subDiv = this._subDiv;
  16751. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16752. this._facetParameters.depthSort = this._facetDepthSort;
  16753. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16754. this.computeWorldMatrix(true);
  16755. this._worldMatrix.invertToRef(this._invertedMatrix);
  16756. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16757. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16758. }
  16759. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16760. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16761. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16762. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16763. var l = (this._depthSortedIndices.length / 3) | 0;
  16764. for (var f = 0; f < l; f++) {
  16765. var sind = this._depthSortedFacets[f].ind;
  16766. this._depthSortedIndices[f * 3] = indices[sind];
  16767. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16768. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16769. }
  16770. this.updateIndices(this._depthSortedIndices);
  16771. }
  16772. return this;
  16773. };
  16774. /**
  16775. * Returns the facetLocalNormals array.
  16776. * The normals are expressed in the mesh local space.
  16777. */
  16778. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16779. if (!this._facetNormals) {
  16780. this.updateFacetData();
  16781. }
  16782. return this._facetNormals;
  16783. };
  16784. /**
  16785. * Returns the facetLocalPositions array.
  16786. * The facet positions are expressed in the mesh local space.
  16787. */
  16788. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16789. if (!this._facetPositions) {
  16790. this.updateFacetData();
  16791. }
  16792. return this._facetPositions;
  16793. };
  16794. /**
  16795. * Returns the facetLocalPartioning array.
  16796. */
  16797. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16798. if (!this._facetPartitioning) {
  16799. this.updateFacetData();
  16800. }
  16801. return this._facetPartitioning;
  16802. };
  16803. /**
  16804. * Returns the i-th facet position in the world system.
  16805. * This method allocates a new Vector3 per call.
  16806. */
  16807. AbstractMesh.prototype.getFacetPosition = function (i) {
  16808. var pos = BABYLON.Vector3.Zero();
  16809. this.getFacetPositionToRef(i, pos);
  16810. return pos;
  16811. };
  16812. /**
  16813. * Sets the reference Vector3 with the i-th facet position in the world system.
  16814. * Returns the AbstractMesh.
  16815. */
  16816. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16817. var localPos = (this.getFacetLocalPositions())[i];
  16818. var world = this.getWorldMatrix();
  16819. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16820. return this;
  16821. };
  16822. /**
  16823. * Returns the i-th facet normal in the world system.
  16824. * This method allocates a new Vector3 per call.
  16825. */
  16826. AbstractMesh.prototype.getFacetNormal = function (i) {
  16827. var norm = BABYLON.Vector3.Zero();
  16828. this.getFacetNormalToRef(i, norm);
  16829. return norm;
  16830. };
  16831. /**
  16832. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16833. * Returns the AbstractMesh.
  16834. */
  16835. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16836. var localNorm = (this.getFacetLocalNormals())[i];
  16837. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16838. return this;
  16839. };
  16840. /**
  16841. * 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).
  16842. */
  16843. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16844. var bInfo = this.getBoundingInfo();
  16845. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16846. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16847. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16848. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16849. return null;
  16850. }
  16851. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16852. };
  16853. /**
  16854. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16855. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16856. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  16857. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16858. * 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.
  16859. */
  16860. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16861. if (checkFace === void 0) { checkFace = false; }
  16862. if (facing === void 0) { facing = true; }
  16863. var world = this.getWorldMatrix();
  16864. var invMat = BABYLON.Tmp.Matrix[5];
  16865. world.invertToRef(invMat);
  16866. var invVect = BABYLON.Tmp.Vector3[8];
  16867. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16868. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16869. if (projected) {
  16870. // tranform the local computed projected vector to world coordinates
  16871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16872. }
  16873. return closest;
  16874. };
  16875. /**
  16876. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16877. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16878. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  16879. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16880. * 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.
  16881. */
  16882. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16883. if (checkFace === void 0) { checkFace = false; }
  16884. if (facing === void 0) { facing = true; }
  16885. var closest = null;
  16886. var tmpx = 0.0;
  16887. var tmpy = 0.0;
  16888. var tmpz = 0.0;
  16889. var d = 0.0; // tmp dot facet normal * facet position
  16890. var t0 = 0.0;
  16891. var projx = 0.0;
  16892. var projy = 0.0;
  16893. var projz = 0.0;
  16894. // Get all the facets in the same partitioning block than (x, y, z)
  16895. var facetPositions = this.getFacetLocalPositions();
  16896. var facetNormals = this.getFacetLocalNormals();
  16897. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16898. if (!facetsInBlock) {
  16899. return null;
  16900. }
  16901. // Get the closest facet to (x, y, z)
  16902. var shortest = Number.MAX_VALUE; // init distance vars
  16903. var tmpDistance = shortest;
  16904. var fib; // current facet in the block
  16905. var norm; // current facet normal
  16906. var p0; // current facet barycenter position
  16907. // loop on all the facets in the current partitioning block
  16908. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16909. fib = facetsInBlock[idx];
  16910. norm = facetNormals[fib];
  16911. p0 = facetPositions[fib];
  16912. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16913. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16914. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16915. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16916. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16917. projx = x + norm.x * t0;
  16918. projy = y + norm.y * t0;
  16919. projz = z + norm.z * t0;
  16920. tmpx = projx - x;
  16921. tmpy = projy - y;
  16922. tmpz = projz - z;
  16923. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16924. if (tmpDistance < shortest) {
  16925. shortest = tmpDistance;
  16926. closest = fib;
  16927. if (projected) {
  16928. projected.x = projx;
  16929. projected.y = projy;
  16930. projected.z = projz;
  16931. }
  16932. }
  16933. }
  16934. }
  16935. return closest;
  16936. };
  16937. /**
  16938. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16939. */
  16940. AbstractMesh.prototype.getFacetDataParameters = function () {
  16941. return this._facetParameters;
  16942. };
  16943. /**
  16944. * Disables the feature FacetData and frees the related memory.
  16945. * Returns the AbstractMesh.
  16946. */
  16947. AbstractMesh.prototype.disableFacetData = function () {
  16948. if (this._facetDataEnabled) {
  16949. this._facetDataEnabled = false;
  16950. this._facetPositions = new Array();
  16951. this._facetNormals = new Array();
  16952. this._facetPartitioning = new Array();
  16953. this._facetParameters = null;
  16954. this._depthSortedIndices = new Uint32Array(0);
  16955. }
  16956. return this;
  16957. };
  16958. /**
  16959. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16960. * Returns the mesh.
  16961. */
  16962. AbstractMesh.prototype.updateIndices = function (indices) {
  16963. return this;
  16964. };
  16965. /**
  16966. * The mesh Geometry. Actually used by the Mesh object.
  16967. * Returns a blank geometry object.
  16968. */
  16969. /**
  16970. * Creates new normals data for the mesh.
  16971. * @param updatable.
  16972. */
  16973. AbstractMesh.prototype.createNormals = function (updatable) {
  16974. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16975. var indices = this.getIndices();
  16976. var normals;
  16977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16978. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16979. }
  16980. else {
  16981. normals = [];
  16982. }
  16983. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16984. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16985. };
  16986. /**
  16987. * Align the mesh with a normal.
  16988. * Returns the mesh.
  16989. */
  16990. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16991. if (!upDirection) {
  16992. upDirection = BABYLON.Axis.Y;
  16993. }
  16994. var axisX = BABYLON.Tmp.Vector3[0];
  16995. var axisZ = BABYLON.Tmp.Vector3[1];
  16996. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16997. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16998. if (this.rotationQuaternion) {
  16999. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17000. }
  17001. else {
  17002. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17003. }
  17004. return this;
  17005. };
  17006. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17007. var engine = this.getEngine();
  17008. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17009. this._isOccluded = false;
  17010. return;
  17011. }
  17012. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17013. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17014. if (isOcclusionQueryAvailable) {
  17015. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17016. this._isOcclusionQueryInProgress = false;
  17017. this._occlusionInternalRetryCounter = 0;
  17018. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17019. }
  17020. else {
  17021. this._occlusionInternalRetryCounter++;
  17022. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17023. this._isOcclusionQueryInProgress = false;
  17024. this._occlusionInternalRetryCounter = 0;
  17025. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17026. // if strict continue the last state of the object.
  17027. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17028. }
  17029. else {
  17030. return;
  17031. }
  17032. }
  17033. }
  17034. var scene = this.getScene();
  17035. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17036. if (!this._occlusionQuery) {
  17037. this._occlusionQuery = engine.createQuery();
  17038. }
  17039. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17040. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17041. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17042. this._isOcclusionQueryInProgress = true;
  17043. };
  17044. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17045. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17046. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17047. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17048. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17049. return AbstractMesh;
  17050. }(BABYLON.TransformNode));
  17051. BABYLON.AbstractMesh = AbstractMesh;
  17052. })(BABYLON || (BABYLON = {}));
  17053. //# sourceMappingURL=babylon.abstractMesh.js.map
  17054. var BABYLON;
  17055. (function (BABYLON) {
  17056. var Light = /** @class */ (function (_super) {
  17057. __extends(Light, _super);
  17058. /**
  17059. * Creates a Light object in the scene.
  17060. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17061. */
  17062. function Light(name, scene) {
  17063. var _this = _super.call(this, name, scene) || this;
  17064. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17065. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17066. _this.intensity = 1.0;
  17067. _this.range = Number.MAX_VALUE;
  17068. /**
  17069. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17070. * of light.
  17071. */
  17072. _this._photometricScale = 1.0;
  17073. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17074. _this._radius = 0.00001;
  17075. _this.renderPriority = 0;
  17076. /**
  17077. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17078. * the current shadow generator.
  17079. */
  17080. _this.shadowEnabled = true;
  17081. _this._excludeWithLayerMask = 0;
  17082. _this._includeOnlyWithLayerMask = 0;
  17083. _this._lightmapMode = 0;
  17084. _this._excludedMeshesIds = new Array();
  17085. _this._includedOnlyMeshesIds = new Array();
  17086. _this.getScene().addLight(_this);
  17087. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17088. _this._buildUniformLayout();
  17089. _this.includedOnlyMeshes = new Array();
  17090. _this.excludedMeshes = new Array();
  17091. _this._resyncMeshes();
  17092. return _this;
  17093. }
  17094. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17095. /**
  17096. * If every light affecting the material is in this lightmapMode,
  17097. * material.lightmapTexture adds or multiplies
  17098. * (depends on material.useLightmapAsShadowmap)
  17099. * after every other light calculations.
  17100. */
  17101. get: function () {
  17102. return Light._LIGHTMAP_DEFAULT;
  17103. },
  17104. enumerable: true,
  17105. configurable: true
  17106. });
  17107. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17108. /**
  17109. * material.lightmapTexture as only diffuse lighting from this light
  17110. * adds only specular lighting from this light
  17111. * adds dynamic shadows
  17112. */
  17113. get: function () {
  17114. return Light._LIGHTMAP_SPECULAR;
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17120. /**
  17121. * material.lightmapTexture as only lighting
  17122. * no light calculation from this light
  17123. * only adds dynamic shadows from this light
  17124. */
  17125. get: function () {
  17126. return Light._LIGHTMAP_SHADOWSONLY;
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17132. /**
  17133. * Each light type uses the default quantity according to its type:
  17134. * point/spot lights use luminous intensity
  17135. * directional lights use illuminance
  17136. */
  17137. get: function () {
  17138. return Light._INTENSITYMODE_AUTOMATIC;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17144. /**
  17145. * lumen (lm)
  17146. */
  17147. get: function () {
  17148. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17154. /**
  17155. * candela (lm/sr)
  17156. */
  17157. get: function () {
  17158. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17164. /**
  17165. * lux (lm/m^2)
  17166. */
  17167. get: function () {
  17168. return Light._INTENSITYMODE_ILLUMINANCE;
  17169. },
  17170. enumerable: true,
  17171. configurable: true
  17172. });
  17173. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17174. /**
  17175. * nit (cd/m^2)
  17176. */
  17177. get: function () {
  17178. return Light._INTENSITYMODE_LUMINANCE;
  17179. },
  17180. enumerable: true,
  17181. configurable: true
  17182. });
  17183. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17184. /**
  17185. * Light type const id of the point light.
  17186. */
  17187. get: function () {
  17188. return Light._LIGHTTYPEID_POINTLIGHT;
  17189. },
  17190. enumerable: true,
  17191. configurable: true
  17192. });
  17193. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17194. /**
  17195. * Light type const id of the directional light.
  17196. */
  17197. get: function () {
  17198. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17199. },
  17200. enumerable: true,
  17201. configurable: true
  17202. });
  17203. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17204. /**
  17205. * Light type const id of the spot light.
  17206. */
  17207. get: function () {
  17208. return Light._LIGHTTYPEID_SPOTLIGHT;
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17214. /**
  17215. * Light type const id of the hemispheric light.
  17216. */
  17217. get: function () {
  17218. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Object.defineProperty(Light.prototype, "intensityMode", {
  17224. /**
  17225. * Gets the photometric scale used to interpret the intensity.
  17226. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17227. */
  17228. get: function () {
  17229. return this._intensityMode;
  17230. },
  17231. /**
  17232. * Sets the photometric scale used to interpret the intensity.
  17233. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17234. */
  17235. set: function (value) {
  17236. this._intensityMode = value;
  17237. this._computePhotometricScale();
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. ;
  17243. ;
  17244. Object.defineProperty(Light.prototype, "radius", {
  17245. /**
  17246. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17247. */
  17248. get: function () {
  17249. return this._radius;
  17250. },
  17251. /**
  17252. * sets the light radius used by PBR Materials to simulate soft area lights.
  17253. */
  17254. set: function (value) {
  17255. this._radius = value;
  17256. this._computePhotometricScale();
  17257. },
  17258. enumerable: true,
  17259. configurable: true
  17260. });
  17261. ;
  17262. ;
  17263. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17264. get: function () {
  17265. return this._includedOnlyMeshes;
  17266. },
  17267. set: function (value) {
  17268. this._includedOnlyMeshes = value;
  17269. this._hookArrayForIncludedOnly(value);
  17270. },
  17271. enumerable: true,
  17272. configurable: true
  17273. });
  17274. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17275. get: function () {
  17276. return this._excludedMeshes;
  17277. },
  17278. set: function (value) {
  17279. this._excludedMeshes = value;
  17280. this._hookArrayForExcluded(value);
  17281. },
  17282. enumerable: true,
  17283. configurable: true
  17284. });
  17285. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17286. get: function () {
  17287. return this._excludeWithLayerMask;
  17288. },
  17289. set: function (value) {
  17290. this._excludeWithLayerMask = value;
  17291. this._resyncMeshes();
  17292. },
  17293. enumerable: true,
  17294. configurable: true
  17295. });
  17296. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17297. get: function () {
  17298. return this._includeOnlyWithLayerMask;
  17299. },
  17300. set: function (value) {
  17301. this._includeOnlyWithLayerMask = value;
  17302. this._resyncMeshes();
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. Object.defineProperty(Light.prototype, "lightmapMode", {
  17308. get: function () {
  17309. return this._lightmapMode;
  17310. },
  17311. set: function (value) {
  17312. if (this._lightmapMode === value) {
  17313. return;
  17314. }
  17315. this._lightmapMode = value;
  17316. this._markMeshesAsLightDirty();
  17317. },
  17318. enumerable: true,
  17319. configurable: true
  17320. });
  17321. Light.prototype._buildUniformLayout = function () {
  17322. // Overridden
  17323. };
  17324. /**
  17325. * Returns the string "Light".
  17326. */
  17327. Light.prototype.getClassName = function () {
  17328. return "Light";
  17329. };
  17330. /**
  17331. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17332. */
  17333. Light.prototype.toString = function (fullDetails) {
  17334. var ret = "Name: " + this.name;
  17335. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17336. if (this.animations) {
  17337. for (var i = 0; i < this.animations.length; i++) {
  17338. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17339. }
  17340. }
  17341. if (fullDetails) {
  17342. }
  17343. return ret;
  17344. };
  17345. /**
  17346. * Set the enabled state of this node.
  17347. * @param {boolean} value - the new enabled state
  17348. * @see isEnabled
  17349. */
  17350. Light.prototype.setEnabled = function (value) {
  17351. _super.prototype.setEnabled.call(this, value);
  17352. this._resyncMeshes();
  17353. };
  17354. /**
  17355. * Returns the Light associated shadow generator.
  17356. */
  17357. Light.prototype.getShadowGenerator = function () {
  17358. return this._shadowGenerator;
  17359. };
  17360. /**
  17361. * Returns a Vector3, the absolute light position in the World.
  17362. */
  17363. Light.prototype.getAbsolutePosition = function () {
  17364. return BABYLON.Vector3.Zero();
  17365. };
  17366. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17367. };
  17368. Light.prototype._getWorldMatrix = function () {
  17369. return BABYLON.Matrix.Identity();
  17370. };
  17371. /**
  17372. * Boolean : True if the light will affect the passed mesh.
  17373. */
  17374. Light.prototype.canAffectMesh = function (mesh) {
  17375. if (!mesh) {
  17376. return true;
  17377. }
  17378. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17379. return false;
  17380. }
  17381. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17382. return false;
  17383. }
  17384. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17385. return false;
  17386. }
  17387. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17388. return false;
  17389. }
  17390. return true;
  17391. };
  17392. /**
  17393. * Returns the light World matrix.
  17394. */
  17395. Light.prototype.getWorldMatrix = function () {
  17396. this._currentRenderId = this.getScene().getRenderId();
  17397. var worldMatrix = this._getWorldMatrix();
  17398. if (this.parent && this.parent.getWorldMatrix) {
  17399. if (!this._parentedWorldMatrix) {
  17400. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17401. }
  17402. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17403. this._markSyncedWithParent();
  17404. return this._parentedWorldMatrix;
  17405. }
  17406. return worldMatrix;
  17407. };
  17408. /**
  17409. * Sort function to order lights for rendering.
  17410. * @param a First Light object to compare to second.
  17411. * @param b Second Light object to compare first.
  17412. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17413. */
  17414. Light.compareLightsPriority = function (a, b) {
  17415. //shadow-casting lights have priority over non-shadow-casting lights
  17416. //the renderPrioirty is a secondary sort criterion
  17417. if (a.shadowEnabled !== b.shadowEnabled) {
  17418. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17419. }
  17420. return b.renderPriority - a.renderPriority;
  17421. };
  17422. /**
  17423. * Disposes the light.
  17424. */
  17425. Light.prototype.dispose = function () {
  17426. if (this._shadowGenerator) {
  17427. this._shadowGenerator.dispose();
  17428. this._shadowGenerator = null;
  17429. }
  17430. // Animations
  17431. this.getScene().stopAnimation(this);
  17432. this._uniformBuffer.dispose();
  17433. // Remove from scene
  17434. this.getScene().removeLight(this);
  17435. _super.prototype.dispose.call(this);
  17436. };
  17437. /**
  17438. * Returns the light type ID (integer).
  17439. */
  17440. Light.prototype.getTypeID = function () {
  17441. return 0;
  17442. };
  17443. /**
  17444. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17445. */
  17446. Light.prototype.getScaledIntensity = function () {
  17447. return this._photometricScale * this.intensity;
  17448. };
  17449. /**
  17450. * Returns a new Light object, named "name", from the current one.
  17451. */
  17452. Light.prototype.clone = function (name) {
  17453. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17454. if (!constructor) {
  17455. return null;
  17456. }
  17457. return BABYLON.SerializationHelper.Clone(constructor, this);
  17458. };
  17459. /**
  17460. * Serializes the current light into a Serialization object.
  17461. * Returns the serialized object.
  17462. */
  17463. Light.prototype.serialize = function () {
  17464. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17465. // Type
  17466. serializationObject.type = this.getTypeID();
  17467. // Parent
  17468. if (this.parent) {
  17469. serializationObject.parentId = this.parent.id;
  17470. }
  17471. // Inclusion / exclusions
  17472. if (this.excludedMeshes.length > 0) {
  17473. serializationObject.excludedMeshesIds = [];
  17474. this.excludedMeshes.forEach(function (mesh) {
  17475. serializationObject.excludedMeshesIds.push(mesh.id);
  17476. });
  17477. }
  17478. if (this.includedOnlyMeshes.length > 0) {
  17479. serializationObject.includedOnlyMeshesIds = [];
  17480. this.includedOnlyMeshes.forEach(function (mesh) {
  17481. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17482. });
  17483. }
  17484. // Animations
  17485. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17486. serializationObject.ranges = this.serializeAnimationRanges();
  17487. return serializationObject;
  17488. };
  17489. /**
  17490. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17491. * This new light is named "name" and added to the passed scene.
  17492. */
  17493. Light.GetConstructorFromName = function (type, name, scene) {
  17494. switch (type) {
  17495. case 0:
  17496. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17497. case 1:
  17498. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17499. case 2:
  17500. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17501. case 3:
  17502. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17503. }
  17504. return null;
  17505. };
  17506. /**
  17507. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17508. */
  17509. Light.Parse = function (parsedLight, scene) {
  17510. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17511. if (!constructor) {
  17512. return null;
  17513. }
  17514. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17515. // Inclusion / exclusions
  17516. if (parsedLight.excludedMeshesIds) {
  17517. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17518. }
  17519. if (parsedLight.includedOnlyMeshesIds) {
  17520. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17521. }
  17522. // Parent
  17523. if (parsedLight.parentId) {
  17524. light._waitingParentId = parsedLight.parentId;
  17525. }
  17526. // Animations
  17527. if (parsedLight.animations) {
  17528. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17529. var parsedAnimation = parsedLight.animations[animationIndex];
  17530. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17531. }
  17532. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17533. }
  17534. if (parsedLight.autoAnimate) {
  17535. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17536. }
  17537. return light;
  17538. };
  17539. Light.prototype._hookArrayForExcluded = function (array) {
  17540. var _this = this;
  17541. var oldPush = array.push;
  17542. array.push = function () {
  17543. var items = [];
  17544. for (var _i = 0; _i < arguments.length; _i++) {
  17545. items[_i] = arguments[_i];
  17546. }
  17547. var result = oldPush.apply(array, items);
  17548. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17549. var item = items_1[_a];
  17550. item._resyncLighSource(_this);
  17551. }
  17552. return result;
  17553. };
  17554. var oldSplice = array.splice;
  17555. array.splice = function (index, deleteCount) {
  17556. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17557. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17558. var item = deleted_1[_i];
  17559. item._resyncLighSource(_this);
  17560. }
  17561. return deleted;
  17562. };
  17563. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17564. var item = array_1[_i];
  17565. item._resyncLighSource(this);
  17566. }
  17567. };
  17568. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17569. var _this = this;
  17570. var oldPush = array.push;
  17571. array.push = function () {
  17572. var items = [];
  17573. for (var _i = 0; _i < arguments.length; _i++) {
  17574. items[_i] = arguments[_i];
  17575. }
  17576. var result = oldPush.apply(array, items);
  17577. _this._resyncMeshes();
  17578. return result;
  17579. };
  17580. var oldSplice = array.splice;
  17581. array.splice = function (index, deleteCount) {
  17582. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17583. _this._resyncMeshes();
  17584. return deleted;
  17585. };
  17586. this._resyncMeshes();
  17587. };
  17588. Light.prototype._resyncMeshes = function () {
  17589. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17590. var mesh = _a[_i];
  17591. mesh._resyncLighSource(this);
  17592. }
  17593. };
  17594. Light.prototype._markMeshesAsLightDirty = function () {
  17595. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17596. var mesh = _a[_i];
  17597. if (mesh._lightSources.indexOf(this) !== -1) {
  17598. mesh._markSubMeshesAsLightDirty();
  17599. }
  17600. }
  17601. };
  17602. /**
  17603. * Recomputes the cached photometric scale if needed.
  17604. */
  17605. Light.prototype._computePhotometricScale = function () {
  17606. this._photometricScale = this._getPhotometricScale();
  17607. this.getScene().resetCachedMaterial();
  17608. };
  17609. /**
  17610. * Returns the Photometric Scale according to the light type and intensity mode.
  17611. */
  17612. Light.prototype._getPhotometricScale = function () {
  17613. var photometricScale = 0.0;
  17614. var lightTypeID = this.getTypeID();
  17615. //get photometric mode
  17616. var photometricMode = this.intensityMode;
  17617. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17618. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17619. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17620. }
  17621. else {
  17622. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17623. }
  17624. }
  17625. //compute photometric scale
  17626. switch (lightTypeID) {
  17627. case Light.LIGHTTYPEID_POINTLIGHT:
  17628. case Light.LIGHTTYPEID_SPOTLIGHT:
  17629. switch (photometricMode) {
  17630. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17631. photometricScale = 1.0 / (4.0 * Math.PI);
  17632. break;
  17633. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17634. photometricScale = 1.0;
  17635. break;
  17636. case Light.INTENSITYMODE_LUMINANCE:
  17637. photometricScale = this.radius * this.radius;
  17638. break;
  17639. }
  17640. break;
  17641. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17642. switch (photometricMode) {
  17643. case Light.INTENSITYMODE_ILLUMINANCE:
  17644. photometricScale = 1.0;
  17645. break;
  17646. case Light.INTENSITYMODE_LUMINANCE:
  17647. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17648. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17649. var apexAngleRadians = this.radius;
  17650. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17651. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17652. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17653. photometricScale = solidAngle;
  17654. break;
  17655. }
  17656. break;
  17657. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17658. // No fall off in hemisperic light.
  17659. photometricScale = 1.0;
  17660. break;
  17661. }
  17662. return photometricScale;
  17663. };
  17664. Light.prototype._reorderLightsInScene = function () {
  17665. var scene = this.getScene();
  17666. if (this._renderPriority != 0) {
  17667. scene.requireLightSorting = true;
  17668. }
  17669. this.getScene().sortLightsByPriority();
  17670. };
  17671. //lightmapMode Consts
  17672. Light._LIGHTMAP_DEFAULT = 0;
  17673. Light._LIGHTMAP_SPECULAR = 1;
  17674. Light._LIGHTMAP_SHADOWSONLY = 2;
  17675. // Intensity Mode Consts
  17676. Light._INTENSITYMODE_AUTOMATIC = 0;
  17677. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17678. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17679. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17680. Light._INTENSITYMODE_LUMINANCE = 4;
  17681. // Light types ids const.
  17682. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17683. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17684. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17685. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17686. __decorate([
  17687. BABYLON.serializeAsColor3()
  17688. ], Light.prototype, "diffuse", void 0);
  17689. __decorate([
  17690. BABYLON.serializeAsColor3()
  17691. ], Light.prototype, "specular", void 0);
  17692. __decorate([
  17693. BABYLON.serialize()
  17694. ], Light.prototype, "intensity", void 0);
  17695. __decorate([
  17696. BABYLON.serialize()
  17697. ], Light.prototype, "range", void 0);
  17698. __decorate([
  17699. BABYLON.serialize()
  17700. ], Light.prototype, "intensityMode", null);
  17701. __decorate([
  17702. BABYLON.serialize()
  17703. ], Light.prototype, "radius", null);
  17704. __decorate([
  17705. BABYLON.serialize()
  17706. ], Light.prototype, "_renderPriority", void 0);
  17707. __decorate([
  17708. BABYLON.expandToProperty("_reorderLightsInScene")
  17709. ], Light.prototype, "renderPriority", void 0);
  17710. __decorate([
  17711. BABYLON.serialize()
  17712. ], Light.prototype, "shadowEnabled", void 0);
  17713. __decorate([
  17714. BABYLON.serialize("excludeWithLayerMask")
  17715. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17716. __decorate([
  17717. BABYLON.serialize("includeOnlyWithLayerMask")
  17718. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17719. __decorate([
  17720. BABYLON.serialize("lightmapMode")
  17721. ], Light.prototype, "_lightmapMode", void 0);
  17722. return Light;
  17723. }(BABYLON.Node));
  17724. BABYLON.Light = Light;
  17725. })(BABYLON || (BABYLON = {}));
  17726. //# sourceMappingURL=babylon.light.js.map
  17727. var BABYLON;
  17728. (function (BABYLON) {
  17729. var Camera = /** @class */ (function (_super) {
  17730. __extends(Camera, _super);
  17731. function Camera(name, position, scene) {
  17732. var _this = _super.call(this, name, scene) || this;
  17733. /**
  17734. * The vector the camera should consider as up.
  17735. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  17736. */
  17737. _this.upVector = BABYLON.Vector3.Up();
  17738. _this.orthoLeft = null;
  17739. _this.orthoRight = null;
  17740. _this.orthoBottom = null;
  17741. _this.orthoTop = null;
  17742. /**
  17743. * FOV is set in Radians. (default is 0.8)
  17744. */
  17745. _this.fov = 0.8;
  17746. _this.minZ = 1;
  17747. _this.maxZ = 10000.0;
  17748. _this.inertia = 0.9;
  17749. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17750. _this.isIntermediate = false;
  17751. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17752. /**
  17753. * Restricts the camera to viewing objects with the same layerMask.
  17754. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  17755. */
  17756. _this.layerMask = 0x0FFFFFFF;
  17757. /**
  17758. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  17759. */
  17760. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17761. // Camera rig members
  17762. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17763. _this._rigCameras = new Array();
  17764. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17765. _this._skipRendering = false;
  17766. _this.customRenderTargets = new Array();
  17767. // Observables
  17768. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17769. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17770. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17771. _this.onRestoreStateObservable = new BABYLON.Observable();
  17772. // Cache
  17773. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17774. _this._projectionMatrix = new BABYLON.Matrix();
  17775. _this._doNotComputeProjectionMatrix = false;
  17776. _this._postProcesses = new Array();
  17777. _this._transformMatrix = BABYLON.Matrix.Zero();
  17778. _this._activeMeshes = new BABYLON.SmartArray(256);
  17779. _this._globalPosition = BABYLON.Vector3.Zero();
  17780. _this._refreshFrustumPlanes = true;
  17781. _this.getScene().addCamera(_this);
  17782. if (!_this.getScene().activeCamera) {
  17783. _this.getScene().activeCamera = _this;
  17784. }
  17785. _this.position = position;
  17786. return _this;
  17787. }
  17788. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17789. get: function () {
  17790. return Camera._PERSPECTIVE_CAMERA;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17796. get: function () {
  17797. return Camera._ORTHOGRAPHIC_CAMERA;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17803. /**
  17804. * This is the default FOV mode for perspective cameras.
  17805. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17806. *
  17807. */
  17808. get: function () {
  17809. return Camera._FOVMODE_VERTICAL_FIXED;
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17815. /**
  17816. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17817. *
  17818. */
  17819. get: function () {
  17820. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17826. get: function () {
  17827. return Camera._RIG_MODE_NONE;
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17833. get: function () {
  17834. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17840. get: function () {
  17841. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17847. get: function () {
  17848. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17854. get: function () {
  17855. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17861. get: function () {
  17862. return Camera._RIG_MODE_VR;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17868. get: function () {
  17869. return Camera._RIG_MODE_WEBVR;
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. /**
  17875. * Store current camera state (fov, position, etc..)
  17876. */
  17877. Camera.prototype.storeState = function () {
  17878. this._stateStored = true;
  17879. this._storedFov = this.fov;
  17880. return this;
  17881. };
  17882. /**
  17883. * Restores the camera state values if it has been stored. You must call storeState() first
  17884. */
  17885. Camera.prototype._restoreStateValues = function () {
  17886. if (!this._stateStored) {
  17887. return false;
  17888. }
  17889. this.fov = this._storedFov;
  17890. return true;
  17891. };
  17892. /**
  17893. * Restored camera state. You must call storeState() first
  17894. */
  17895. Camera.prototype.restoreState = function () {
  17896. if (this._restoreStateValues()) {
  17897. this.onRestoreStateObservable.notifyObservers(this);
  17898. return true;
  17899. }
  17900. return false;
  17901. };
  17902. Camera.prototype.getClassName = function () {
  17903. return "Camera";
  17904. };
  17905. /**
  17906. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17907. */
  17908. Camera.prototype.toString = function (fullDetails) {
  17909. var ret = "Name: " + this.name;
  17910. ret += ", type: " + this.getClassName();
  17911. if (this.animations) {
  17912. for (var i = 0; i < this.animations.length; i++) {
  17913. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17914. }
  17915. }
  17916. if (fullDetails) {
  17917. }
  17918. return ret;
  17919. };
  17920. Object.defineProperty(Camera.prototype, "globalPosition", {
  17921. get: function () {
  17922. return this._globalPosition;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. Camera.prototype.getActiveMeshes = function () {
  17928. return this._activeMeshes;
  17929. };
  17930. Camera.prototype.isActiveMesh = function (mesh) {
  17931. return (this._activeMeshes.indexOf(mesh) !== -1);
  17932. };
  17933. //Cache
  17934. Camera.prototype._initCache = function () {
  17935. _super.prototype._initCache.call(this);
  17936. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17937. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17938. this._cache.mode = undefined;
  17939. this._cache.minZ = undefined;
  17940. this._cache.maxZ = undefined;
  17941. this._cache.fov = undefined;
  17942. this._cache.fovMode = undefined;
  17943. this._cache.aspectRatio = undefined;
  17944. this._cache.orthoLeft = undefined;
  17945. this._cache.orthoRight = undefined;
  17946. this._cache.orthoBottom = undefined;
  17947. this._cache.orthoTop = undefined;
  17948. this._cache.renderWidth = undefined;
  17949. this._cache.renderHeight = undefined;
  17950. };
  17951. Camera.prototype._updateCache = function (ignoreParentClass) {
  17952. if (!ignoreParentClass) {
  17953. _super.prototype._updateCache.call(this);
  17954. }
  17955. this._cache.position.copyFrom(this.position);
  17956. this._cache.upVector.copyFrom(this.upVector);
  17957. };
  17958. // Synchronized
  17959. Camera.prototype._isSynchronized = function () {
  17960. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17961. };
  17962. Camera.prototype._isSynchronizedViewMatrix = function () {
  17963. if (!_super.prototype._isSynchronized.call(this))
  17964. return false;
  17965. return this._cache.position.equals(this.position)
  17966. && this._cache.upVector.equals(this.upVector)
  17967. && this.isSynchronizedWithParent();
  17968. };
  17969. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17970. var check = this._cache.mode === this.mode
  17971. && this._cache.minZ === this.minZ
  17972. && this._cache.maxZ === this.maxZ;
  17973. if (!check) {
  17974. return false;
  17975. }
  17976. var engine = this.getEngine();
  17977. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17978. check = this._cache.fov === this.fov
  17979. && this._cache.fovMode === this.fovMode
  17980. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17981. }
  17982. else {
  17983. check = this._cache.orthoLeft === this.orthoLeft
  17984. && this._cache.orthoRight === this.orthoRight
  17985. && this._cache.orthoBottom === this.orthoBottom
  17986. && this._cache.orthoTop === this.orthoTop
  17987. && this._cache.renderWidth === engine.getRenderWidth()
  17988. && this._cache.renderHeight === engine.getRenderHeight();
  17989. }
  17990. return check;
  17991. };
  17992. // Controls
  17993. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17994. };
  17995. Camera.prototype.detachControl = function (element) {
  17996. };
  17997. Camera.prototype.update = function () {
  17998. this._checkInputs();
  17999. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18000. this._updateRigCameras();
  18001. }
  18002. };
  18003. Camera.prototype._checkInputs = function () {
  18004. this.onAfterCheckInputsObservable.notifyObservers(this);
  18005. };
  18006. Object.defineProperty(Camera.prototype, "rigCameras", {
  18007. get: function () {
  18008. return this._rigCameras;
  18009. },
  18010. enumerable: true,
  18011. configurable: true
  18012. });
  18013. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18014. get: function () {
  18015. return this._rigPostProcess;
  18016. },
  18017. enumerable: true,
  18018. configurable: true
  18019. });
  18020. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18021. // invalidate framebuffer
  18022. if (this._postProcesses.length > 0) {
  18023. this._postProcesses[0].markTextureDirty();
  18024. }
  18025. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18026. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18027. var cam = this._rigCameras[i];
  18028. var rigPostProcess = cam._rigPostProcess;
  18029. // for VR rig, there does not have to be a post process
  18030. if (rigPostProcess) {
  18031. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18032. if (isPass) {
  18033. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18034. cam.isIntermediate = this._postProcesses.length === 0;
  18035. }
  18036. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18037. rigPostProcess.markTextureDirty();
  18038. }
  18039. else {
  18040. cam._postProcesses = this._postProcesses.slice(0);
  18041. }
  18042. }
  18043. };
  18044. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18045. if (insertAt === void 0) { insertAt = null; }
  18046. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18047. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18048. return 0;
  18049. }
  18050. if (insertAt == null || insertAt < 0) {
  18051. this._postProcesses.push(postProcess);
  18052. }
  18053. else {
  18054. this._postProcesses.splice(insertAt, 0, postProcess);
  18055. }
  18056. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18057. return this._postProcesses.indexOf(postProcess);
  18058. };
  18059. Camera.prototype.detachPostProcess = function (postProcess) {
  18060. var idx = this._postProcesses.indexOf(postProcess);
  18061. if (idx !== -1) {
  18062. this._postProcesses.splice(idx, 1);
  18063. }
  18064. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18065. };
  18066. Camera.prototype.getWorldMatrix = function () {
  18067. if (!this._worldMatrix) {
  18068. this._worldMatrix = BABYLON.Matrix.Identity();
  18069. }
  18070. var viewMatrix = this.getViewMatrix();
  18071. viewMatrix.invertToRef(this._worldMatrix);
  18072. return this._worldMatrix;
  18073. };
  18074. Camera.prototype._getViewMatrix = function () {
  18075. return BABYLON.Matrix.Identity();
  18076. };
  18077. Camera.prototype.getViewMatrix = function (force) {
  18078. if (!force && this._isSynchronizedViewMatrix()) {
  18079. return this._computedViewMatrix;
  18080. }
  18081. this.updateCache();
  18082. this._computedViewMatrix = this._getViewMatrix();
  18083. this._currentRenderId = this.getScene().getRenderId();
  18084. this._refreshFrustumPlanes = true;
  18085. if (!this.parent || !this.parent.getWorldMatrix) {
  18086. this._globalPosition.copyFrom(this.position);
  18087. }
  18088. else {
  18089. if (!this._worldMatrix) {
  18090. this._worldMatrix = BABYLON.Matrix.Identity();
  18091. }
  18092. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18093. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18094. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18095. this._computedViewMatrix.invert();
  18096. this._markSyncedWithParent();
  18097. }
  18098. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18099. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18100. }
  18101. this.onViewMatrixChangedObservable.notifyObservers(this);
  18102. return this._computedViewMatrix;
  18103. };
  18104. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18105. this._doNotComputeProjectionMatrix = true;
  18106. if (projection !== undefined) {
  18107. this._projectionMatrix = projection;
  18108. }
  18109. };
  18110. ;
  18111. Camera.prototype.unfreezeProjectionMatrix = function () {
  18112. this._doNotComputeProjectionMatrix = false;
  18113. };
  18114. ;
  18115. Camera.prototype.getProjectionMatrix = function (force) {
  18116. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18117. return this._projectionMatrix;
  18118. }
  18119. // Cache
  18120. this._cache.mode = this.mode;
  18121. this._cache.minZ = this.minZ;
  18122. this._cache.maxZ = this.maxZ;
  18123. // Matrix
  18124. this._refreshFrustumPlanes = true;
  18125. var engine = this.getEngine();
  18126. var scene = this.getScene();
  18127. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18128. this._cache.fov = this.fov;
  18129. this._cache.fovMode = this.fovMode;
  18130. this._cache.aspectRatio = engine.getAspectRatio(this);
  18131. if (this.minZ <= 0) {
  18132. this.minZ = 0.1;
  18133. }
  18134. if (scene.useRightHandedSystem) {
  18135. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18136. }
  18137. else {
  18138. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18139. }
  18140. }
  18141. else {
  18142. var halfWidth = engine.getRenderWidth() / 2.0;
  18143. var halfHeight = engine.getRenderHeight() / 2.0;
  18144. if (scene.useRightHandedSystem) {
  18145. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18146. }
  18147. else {
  18148. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18149. }
  18150. this._cache.orthoLeft = this.orthoLeft;
  18151. this._cache.orthoRight = this.orthoRight;
  18152. this._cache.orthoBottom = this.orthoBottom;
  18153. this._cache.orthoTop = this.orthoTop;
  18154. this._cache.renderWidth = engine.getRenderWidth();
  18155. this._cache.renderHeight = engine.getRenderHeight();
  18156. }
  18157. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18158. return this._projectionMatrix;
  18159. };
  18160. Camera.prototype.getTranformationMatrix = function () {
  18161. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18162. return this._transformMatrix;
  18163. };
  18164. Camera.prototype.updateFrustumPlanes = function () {
  18165. if (!this._refreshFrustumPlanes) {
  18166. return;
  18167. }
  18168. this.getTranformationMatrix();
  18169. if (!this._frustumPlanes) {
  18170. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18171. }
  18172. else {
  18173. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18174. }
  18175. this._refreshFrustumPlanes = false;
  18176. };
  18177. Camera.prototype.isInFrustum = function (target) {
  18178. this.updateFrustumPlanes();
  18179. return target.isInFrustum(this._frustumPlanes);
  18180. };
  18181. Camera.prototype.isCompletelyInFrustum = function (target) {
  18182. this.updateFrustumPlanes();
  18183. return target.isCompletelyInFrustum(this._frustumPlanes);
  18184. };
  18185. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18186. if (length === void 0) { length = 100; }
  18187. if (!transform) {
  18188. transform = this.getWorldMatrix();
  18189. }
  18190. if (!origin) {
  18191. origin = this.position;
  18192. }
  18193. var forward = new BABYLON.Vector3(0, 0, 1);
  18194. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18195. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18196. return new BABYLON.Ray(origin, direction, length);
  18197. };
  18198. Camera.prototype.dispose = function () {
  18199. // Observables
  18200. this.onViewMatrixChangedObservable.clear();
  18201. this.onProjectionMatrixChangedObservable.clear();
  18202. this.onAfterCheckInputsObservable.clear();
  18203. this.onRestoreStateObservable.clear();
  18204. // Inputs
  18205. if (this.inputs) {
  18206. this.inputs.clear();
  18207. }
  18208. // Animations
  18209. this.getScene().stopAnimation(this);
  18210. // Remove from scene
  18211. this.getScene().removeCamera(this);
  18212. while (this._rigCameras.length > 0) {
  18213. var camera = this._rigCameras.pop();
  18214. if (camera) {
  18215. camera.dispose();
  18216. }
  18217. }
  18218. // Postprocesses
  18219. if (this._rigPostProcess) {
  18220. this._rigPostProcess.dispose(this);
  18221. this._rigPostProcess = null;
  18222. this._postProcesses = [];
  18223. }
  18224. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18225. this._rigPostProcess = null;
  18226. this._postProcesses = [];
  18227. }
  18228. else {
  18229. var i = this._postProcesses.length;
  18230. while (--i >= 0) {
  18231. this._postProcesses[i].dispose(this);
  18232. }
  18233. }
  18234. // Render targets
  18235. var i = this.customRenderTargets.length;
  18236. while (--i >= 0) {
  18237. this.customRenderTargets[i].dispose();
  18238. }
  18239. this.customRenderTargets = [];
  18240. // Active Meshes
  18241. this._activeMeshes.dispose();
  18242. _super.prototype.dispose.call(this);
  18243. };
  18244. Object.defineProperty(Camera.prototype, "leftCamera", {
  18245. // ---- Camera rigs section ----
  18246. get: function () {
  18247. if (this._rigCameras.length < 1) {
  18248. return null;
  18249. }
  18250. return this._rigCameras[0];
  18251. },
  18252. enumerable: true,
  18253. configurable: true
  18254. });
  18255. Object.defineProperty(Camera.prototype, "rightCamera", {
  18256. get: function () {
  18257. if (this._rigCameras.length < 2) {
  18258. return null;
  18259. }
  18260. return this._rigCameras[1];
  18261. },
  18262. enumerable: true,
  18263. configurable: true
  18264. });
  18265. Camera.prototype.getLeftTarget = function () {
  18266. if (this._rigCameras.length < 1) {
  18267. return null;
  18268. }
  18269. return this._rigCameras[0].getTarget();
  18270. };
  18271. Camera.prototype.getRightTarget = function () {
  18272. if (this._rigCameras.length < 2) {
  18273. return null;
  18274. }
  18275. return this._rigCameras[1].getTarget();
  18276. };
  18277. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18278. if (this.cameraRigMode === mode) {
  18279. return;
  18280. }
  18281. while (this._rigCameras.length > 0) {
  18282. var camera = this._rigCameras.pop();
  18283. if (camera) {
  18284. camera.dispose();
  18285. }
  18286. }
  18287. this.cameraRigMode = mode;
  18288. this._cameraRigParams = {};
  18289. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18290. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18291. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18292. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18293. // create the rig cameras, unless none
  18294. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18295. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18296. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18297. if (leftCamera && rightCamera) {
  18298. this._rigCameras.push(leftCamera);
  18299. this._rigCameras.push(rightCamera);
  18300. }
  18301. }
  18302. switch (this.cameraRigMode) {
  18303. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18304. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18305. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18306. break;
  18307. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18308. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18309. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18310. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18311. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18312. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18313. break;
  18314. case Camera.RIG_MODE_VR:
  18315. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18316. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18317. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18318. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18319. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18320. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18321. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18322. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18323. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18324. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18325. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18326. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18327. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18328. if (metrics.compensateDistortion) {
  18329. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18330. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18331. }
  18332. break;
  18333. case Camera.RIG_MODE_WEBVR:
  18334. if (rigParams.vrDisplay) {
  18335. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18336. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18337. //Left eye
  18338. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18339. this._rigCameras[0].setCameraRigParameter("left", true);
  18340. //leaving this for future reference
  18341. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18342. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18343. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18344. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18345. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18346. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18347. this._rigCameras[0].parent = this;
  18348. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18349. //Right eye
  18350. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18351. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18352. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18353. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18354. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18355. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18356. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18357. this._rigCameras[1].parent = this;
  18358. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18359. if (Camera.UseAlternateWebVRRendering) {
  18360. this._rigCameras[1]._skipRendering = true;
  18361. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18362. }
  18363. }
  18364. break;
  18365. }
  18366. this._cascadePostProcessesToRigCams();
  18367. this.update();
  18368. };
  18369. Camera.prototype._getVRProjectionMatrix = function () {
  18370. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18371. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18372. return this._projectionMatrix;
  18373. };
  18374. Camera.prototype._updateCameraRotationMatrix = function () {
  18375. //Here for WebVR
  18376. };
  18377. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18378. //Here for WebVR
  18379. };
  18380. /**
  18381. * This function MUST be overwritten by the different WebVR cameras available.
  18382. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18383. */
  18384. Camera.prototype._getWebVRProjectionMatrix = function () {
  18385. return BABYLON.Matrix.Identity();
  18386. };
  18387. /**
  18388. * This function MUST be overwritten by the different WebVR cameras available.
  18389. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18390. */
  18391. Camera.prototype._getWebVRViewMatrix = function () {
  18392. return BABYLON.Matrix.Identity();
  18393. };
  18394. Camera.prototype.setCameraRigParameter = function (name, value) {
  18395. if (!this._cameraRigParams) {
  18396. this._cameraRigParams = {};
  18397. }
  18398. this._cameraRigParams[name] = value;
  18399. //provisionnally:
  18400. if (name === "interaxialDistance") {
  18401. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18402. }
  18403. };
  18404. /**
  18405. * needs to be overridden by children so sub has required properties to be copied
  18406. */
  18407. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18408. return null;
  18409. };
  18410. /**
  18411. * May need to be overridden by children
  18412. */
  18413. Camera.prototype._updateRigCameras = function () {
  18414. for (var i = 0; i < this._rigCameras.length; i++) {
  18415. this._rigCameras[i].minZ = this.minZ;
  18416. this._rigCameras[i].maxZ = this.maxZ;
  18417. this._rigCameras[i].fov = this.fov;
  18418. }
  18419. // only update viewport when ANAGLYPH
  18420. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18421. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18422. }
  18423. };
  18424. Camera.prototype._setupInputs = function () {
  18425. };
  18426. Camera.prototype.serialize = function () {
  18427. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18428. // Type
  18429. serializationObject.type = this.getClassName();
  18430. // Parent
  18431. if (this.parent) {
  18432. serializationObject.parentId = this.parent.id;
  18433. }
  18434. if (this.inputs) {
  18435. this.inputs.serialize(serializationObject);
  18436. }
  18437. // Animations
  18438. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18439. serializationObject.ranges = this.serializeAnimationRanges();
  18440. return serializationObject;
  18441. };
  18442. Camera.prototype.clone = function (name) {
  18443. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18444. };
  18445. Camera.prototype.getDirection = function (localAxis) {
  18446. var result = BABYLON.Vector3.Zero();
  18447. this.getDirectionToRef(localAxis, result);
  18448. return result;
  18449. };
  18450. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18451. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18452. };
  18453. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18454. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18455. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18456. switch (type) {
  18457. case "ArcRotateCamera":
  18458. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18459. case "DeviceOrientationCamera":
  18460. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18461. case "FollowCamera":
  18462. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18463. case "ArcFollowCamera":
  18464. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18465. case "GamepadCamera":
  18466. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18467. case "TouchCamera":
  18468. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18469. case "VirtualJoysticksCamera":
  18470. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18471. case "WebVRFreeCamera":
  18472. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18473. case "WebVRGamepadCamera":
  18474. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18475. case "VRDeviceOrientationFreeCamera":
  18476. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18477. case "VRDeviceOrientationGamepadCamera":
  18478. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18479. case "AnaglyphArcRotateCamera":
  18480. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18481. case "AnaglyphFreeCamera":
  18482. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18483. case "AnaglyphGamepadCamera":
  18484. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18485. case "AnaglyphUniversalCamera":
  18486. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18487. case "StereoscopicArcRotateCamera":
  18488. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18489. case "StereoscopicFreeCamera":
  18490. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18491. case "StereoscopicGamepadCamera":
  18492. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18493. case "StereoscopicUniversalCamera":
  18494. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18495. case "FreeCamera":// Forcing Universal here
  18496. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18497. default:// Universal Camera is the default value
  18498. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18499. }
  18500. };
  18501. Camera.prototype.computeWorldMatrix = function () {
  18502. return this.getWorldMatrix();
  18503. };
  18504. Camera.Parse = function (parsedCamera, scene) {
  18505. var type = parsedCamera.type;
  18506. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18507. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18508. // Parent
  18509. if (parsedCamera.parentId) {
  18510. camera._waitingParentId = parsedCamera.parentId;
  18511. }
  18512. //If camera has an input manager, let it parse inputs settings
  18513. if (camera.inputs) {
  18514. camera.inputs.parse(parsedCamera);
  18515. camera._setupInputs();
  18516. }
  18517. if (camera.setPosition) {
  18518. camera.position.copyFromFloats(0, 0, 0);
  18519. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18520. }
  18521. // Target
  18522. if (parsedCamera.target) {
  18523. if (camera.setTarget) {
  18524. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18525. }
  18526. }
  18527. // Apply 3d rig, when found
  18528. if (parsedCamera.cameraRigMode) {
  18529. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18530. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18531. }
  18532. // Animations
  18533. if (parsedCamera.animations) {
  18534. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18535. var parsedAnimation = parsedCamera.animations[animationIndex];
  18536. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18537. }
  18538. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18539. }
  18540. if (parsedCamera.autoAnimate) {
  18541. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18542. }
  18543. return camera;
  18544. };
  18545. // Statics
  18546. Camera._PERSPECTIVE_CAMERA = 0;
  18547. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18548. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18549. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18550. Camera._RIG_MODE_NONE = 0;
  18551. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18552. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18553. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18554. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18555. Camera._RIG_MODE_VR = 20;
  18556. Camera._RIG_MODE_WEBVR = 21;
  18557. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18558. Camera.UseAlternateWebVRRendering = false;
  18559. __decorate([
  18560. BABYLON.serializeAsVector3()
  18561. ], Camera.prototype, "position", void 0);
  18562. __decorate([
  18563. BABYLON.serializeAsVector3()
  18564. ], Camera.prototype, "upVector", void 0);
  18565. __decorate([
  18566. BABYLON.serialize()
  18567. ], Camera.prototype, "orthoLeft", void 0);
  18568. __decorate([
  18569. BABYLON.serialize()
  18570. ], Camera.prototype, "orthoRight", void 0);
  18571. __decorate([
  18572. BABYLON.serialize()
  18573. ], Camera.prototype, "orthoBottom", void 0);
  18574. __decorate([
  18575. BABYLON.serialize()
  18576. ], Camera.prototype, "orthoTop", void 0);
  18577. __decorate([
  18578. BABYLON.serialize()
  18579. ], Camera.prototype, "fov", void 0);
  18580. __decorate([
  18581. BABYLON.serialize()
  18582. ], Camera.prototype, "minZ", void 0);
  18583. __decorate([
  18584. BABYLON.serialize()
  18585. ], Camera.prototype, "maxZ", void 0);
  18586. __decorate([
  18587. BABYLON.serialize()
  18588. ], Camera.prototype, "inertia", void 0);
  18589. __decorate([
  18590. BABYLON.serialize()
  18591. ], Camera.prototype, "mode", void 0);
  18592. __decorate([
  18593. BABYLON.serialize()
  18594. ], Camera.prototype, "layerMask", void 0);
  18595. __decorate([
  18596. BABYLON.serialize()
  18597. ], Camera.prototype, "fovMode", void 0);
  18598. __decorate([
  18599. BABYLON.serialize()
  18600. ], Camera.prototype, "cameraRigMode", void 0);
  18601. __decorate([
  18602. BABYLON.serialize()
  18603. ], Camera.prototype, "interaxialDistance", void 0);
  18604. __decorate([
  18605. BABYLON.serialize()
  18606. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18607. return Camera;
  18608. }(BABYLON.Node));
  18609. BABYLON.Camera = Camera;
  18610. })(BABYLON || (BABYLON = {}));
  18611. //# sourceMappingURL=babylon.camera.js.map
  18612. var BABYLON;
  18613. (function (BABYLON) {
  18614. var RenderingManager = /** @class */ (function () {
  18615. function RenderingManager(scene) {
  18616. this._renderingGroups = new Array();
  18617. this._autoClearDepthStencil = {};
  18618. this._customOpaqueSortCompareFn = {};
  18619. this._customAlphaTestSortCompareFn = {};
  18620. this._customTransparentSortCompareFn = {};
  18621. this._renderinGroupInfo = null;
  18622. this._scene = scene;
  18623. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18624. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18625. }
  18626. }
  18627. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18628. if (depth === void 0) { depth = true; }
  18629. if (stencil === void 0) { stencil = true; }
  18630. if (this._depthStencilBufferAlreadyCleaned) {
  18631. return;
  18632. }
  18633. this._scene.getEngine().clear(null, false, depth, stencil);
  18634. this._depthStencilBufferAlreadyCleaned = true;
  18635. };
  18636. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18637. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18638. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18639. var info = null;
  18640. if (observable) {
  18641. if (!this._renderinGroupInfo) {
  18642. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18643. }
  18644. info = this._renderinGroupInfo;
  18645. info.scene = this._scene;
  18646. info.camera = this._scene.activeCamera;
  18647. }
  18648. // Dispatch sprites
  18649. if (renderSprites) {
  18650. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18651. var manager = this._scene.spriteManagers[index];
  18652. this.dispatchSprites(manager);
  18653. }
  18654. }
  18655. // Render
  18656. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18657. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18658. var renderingGroup = this._renderingGroups[index];
  18659. if (!renderingGroup && !observable)
  18660. continue;
  18661. var renderingGroupMask = 0;
  18662. // Fire PRECLEAR stage
  18663. if (observable && info) {
  18664. renderingGroupMask = Math.pow(2, index);
  18665. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18666. info.renderingGroupId = index;
  18667. observable.notifyObservers(info, renderingGroupMask);
  18668. }
  18669. // Clear depth/stencil if needed
  18670. if (RenderingManager.AUTOCLEAR) {
  18671. var autoClear = this._autoClearDepthStencil[index];
  18672. if (autoClear && autoClear.autoClear) {
  18673. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18674. }
  18675. }
  18676. if (observable && info) {
  18677. // Fire PREOPAQUE stage
  18678. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18679. observable.notifyObservers(info, renderingGroupMask);
  18680. // Fire PRETRANSPARENT stage
  18681. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18682. observable.notifyObservers(info, renderingGroupMask);
  18683. }
  18684. if (renderingGroup)
  18685. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18686. // Fire POSTTRANSPARENT stage
  18687. if (observable && info) {
  18688. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18689. observable.notifyObservers(info, renderingGroupMask);
  18690. }
  18691. }
  18692. };
  18693. RenderingManager.prototype.reset = function () {
  18694. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18695. var renderingGroup = this._renderingGroups[index];
  18696. if (renderingGroup) {
  18697. renderingGroup.prepare();
  18698. }
  18699. }
  18700. };
  18701. RenderingManager.prototype.dispose = function () {
  18702. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18703. var renderingGroup = this._renderingGroups[index];
  18704. if (renderingGroup) {
  18705. renderingGroup.dispose();
  18706. }
  18707. }
  18708. this._renderingGroups.length = 0;
  18709. };
  18710. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18711. if (this._renderingGroups[renderingGroupId] === undefined) {
  18712. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18713. }
  18714. };
  18715. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18716. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18717. this._prepareRenderingGroup(renderingGroupId);
  18718. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18719. };
  18720. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18721. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18722. this._prepareRenderingGroup(renderingGroupId);
  18723. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18724. };
  18725. /**
  18726. * @param subMesh The submesh to dispatch
  18727. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18728. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18729. */
  18730. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18731. if (mesh === undefined) {
  18732. mesh = subMesh.getMesh();
  18733. }
  18734. var renderingGroupId = mesh.renderingGroupId || 0;
  18735. this._prepareRenderingGroup(renderingGroupId);
  18736. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18737. };
  18738. /**
  18739. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18740. * This allowed control for front to back rendering or reversly depending of the special needs.
  18741. *
  18742. * @param renderingGroupId The rendering group id corresponding to its index
  18743. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18744. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18745. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18746. */
  18747. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18748. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18749. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18750. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18751. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18752. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18753. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18754. if (this._renderingGroups[renderingGroupId]) {
  18755. var group = this._renderingGroups[renderingGroupId];
  18756. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18757. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18758. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18759. }
  18760. };
  18761. /**
  18762. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18763. *
  18764. * @param renderingGroupId The rendering group id corresponding to its index
  18765. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18766. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18767. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18768. */
  18769. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18770. if (depth === void 0) { depth = true; }
  18771. if (stencil === void 0) { stencil = true; }
  18772. this._autoClearDepthStencil[renderingGroupId] = {
  18773. autoClear: autoClearDepthStencil,
  18774. depth: depth,
  18775. stencil: stencil
  18776. };
  18777. };
  18778. /**
  18779. * The max id used for rendering groups (not included)
  18780. */
  18781. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18782. /**
  18783. * The min id used for rendering groups (included)
  18784. */
  18785. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18786. /**
  18787. * Used to globally prevent autoclearing scenes.
  18788. */
  18789. RenderingManager.AUTOCLEAR = true;
  18790. return RenderingManager;
  18791. }());
  18792. BABYLON.RenderingManager = RenderingManager;
  18793. })(BABYLON || (BABYLON = {}));
  18794. //# sourceMappingURL=babylon.renderingManager.js.map
  18795. var BABYLON;
  18796. (function (BABYLON) {
  18797. var RenderingGroup = /** @class */ (function () {
  18798. /**
  18799. * Creates a new rendering group.
  18800. * @param index The rendering group index
  18801. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18802. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18803. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18804. */
  18805. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18806. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18807. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18808. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18809. this.index = index;
  18810. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18811. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18812. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18813. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18814. this._particleSystems = new BABYLON.SmartArray(256);
  18815. this._spriteManagers = new BABYLON.SmartArray(256);
  18816. this._edgesRenderers = new BABYLON.SmartArray(16);
  18817. this._scene = scene;
  18818. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18819. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18820. this.transparentSortCompareFn = transparentSortCompareFn;
  18821. }
  18822. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18823. /**
  18824. * Set the opaque sort comparison function.
  18825. * If null the sub meshes will be render in the order they were created
  18826. */
  18827. set: function (value) {
  18828. this._opaqueSortCompareFn = value;
  18829. if (value) {
  18830. this._renderOpaque = this.renderOpaqueSorted;
  18831. }
  18832. else {
  18833. this._renderOpaque = RenderingGroup.renderUnsorted;
  18834. }
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18840. /**
  18841. * Set the alpha test sort comparison function.
  18842. * If null the sub meshes will be render in the order they were created
  18843. */
  18844. set: function (value) {
  18845. this._alphaTestSortCompareFn = value;
  18846. if (value) {
  18847. this._renderAlphaTest = this.renderAlphaTestSorted;
  18848. }
  18849. else {
  18850. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18851. }
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18857. /**
  18858. * Set the transparent sort comparison function.
  18859. * If null the sub meshes will be render in the order they were created
  18860. */
  18861. set: function (value) {
  18862. if (value) {
  18863. this._transparentSortCompareFn = value;
  18864. }
  18865. else {
  18866. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18867. }
  18868. this._renderTransparent = this.renderTransparentSorted;
  18869. },
  18870. enumerable: true,
  18871. configurable: true
  18872. });
  18873. /**
  18874. * Render all the sub meshes contained in the group.
  18875. * @param customRenderFunction Used to override the default render behaviour of the group.
  18876. * @returns true if rendered some submeshes.
  18877. */
  18878. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18879. if (customRenderFunction) {
  18880. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18881. return;
  18882. }
  18883. var engine = this._scene.getEngine();
  18884. // Depth only
  18885. if (this._depthOnlySubMeshes.length !== 0) {
  18886. engine.setColorWrite(false);
  18887. this._renderAlphaTest(this._depthOnlySubMeshes);
  18888. engine.setColorWrite(true);
  18889. }
  18890. // Opaque
  18891. if (this._opaqueSubMeshes.length !== 0) {
  18892. this._renderOpaque(this._opaqueSubMeshes);
  18893. }
  18894. // Alpha test
  18895. if (this._alphaTestSubMeshes.length !== 0) {
  18896. this._renderAlphaTest(this._alphaTestSubMeshes);
  18897. }
  18898. var stencilState = engine.getStencilBuffer();
  18899. engine.setStencilBuffer(false);
  18900. // Sprites
  18901. if (renderSprites) {
  18902. this._renderSprites();
  18903. }
  18904. // Particles
  18905. if (renderParticles) {
  18906. this._renderParticles(activeMeshes);
  18907. }
  18908. if (this.onBeforeTransparentRendering) {
  18909. this.onBeforeTransparentRendering();
  18910. }
  18911. // Transparent
  18912. if (this._transparentSubMeshes.length !== 0) {
  18913. this._renderTransparent(this._transparentSubMeshes);
  18914. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18915. }
  18916. // Set back stencil to false in case it changes before the edge renderer.
  18917. engine.setStencilBuffer(false);
  18918. // Edges
  18919. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18920. this._edgesRenderers.data[edgesRendererIndex].render();
  18921. }
  18922. // Restore Stencil state.
  18923. engine.setStencilBuffer(stencilState);
  18924. };
  18925. /**
  18926. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18927. * @param subMeshes The submeshes to render
  18928. */
  18929. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18930. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18931. };
  18932. /**
  18933. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18934. * @param subMeshes The submeshes to render
  18935. */
  18936. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18937. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18938. };
  18939. /**
  18940. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18941. * @param subMeshes The submeshes to render
  18942. */
  18943. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18944. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18945. };
  18946. /**
  18947. * Renders the submeshes in a specified order.
  18948. * @param subMeshes The submeshes to sort before render
  18949. * @param sortCompareFn The comparison function use to sort
  18950. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18951. * @param transparent Specifies to activate blending if true
  18952. */
  18953. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18954. var subIndex = 0;
  18955. var subMesh;
  18956. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18957. for (; subIndex < subMeshes.length; subIndex++) {
  18958. subMesh = subMeshes.data[subIndex];
  18959. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18960. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18961. }
  18962. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18963. if (sortCompareFn) {
  18964. sortedArray.sort(sortCompareFn);
  18965. }
  18966. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18967. subMesh = sortedArray[subIndex];
  18968. if (transparent) {
  18969. var material = subMesh.getMaterial();
  18970. if (material && material.needDepthPrePass) {
  18971. var engine = material.getScene().getEngine();
  18972. engine.setColorWrite(false);
  18973. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18974. subMesh.render(false);
  18975. engine.setColorWrite(true);
  18976. }
  18977. }
  18978. subMesh.render(transparent);
  18979. }
  18980. };
  18981. /**
  18982. * Renders the submeshes in the order they were dispatched (no sort applied).
  18983. * @param subMeshes The submeshes to render
  18984. */
  18985. RenderingGroup.renderUnsorted = function (subMeshes) {
  18986. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18987. var submesh = subMeshes.data[subIndex];
  18988. submesh.render(false);
  18989. }
  18990. };
  18991. /**
  18992. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18993. * are rendered back to front if in the same alpha index.
  18994. *
  18995. * @param a The first submesh
  18996. * @param b The second submesh
  18997. * @returns The result of the comparison
  18998. */
  18999. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19000. // Alpha index first
  19001. if (a._alphaIndex > b._alphaIndex) {
  19002. return 1;
  19003. }
  19004. if (a._alphaIndex < b._alphaIndex) {
  19005. return -1;
  19006. }
  19007. // Then distance to camera
  19008. return RenderingGroup.backToFrontSortCompare(a, b);
  19009. };
  19010. /**
  19011. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19012. * are rendered back to front.
  19013. *
  19014. * @param a The first submesh
  19015. * @param b The second submesh
  19016. * @returns The result of the comparison
  19017. */
  19018. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19019. // Then distance to camera
  19020. if (a._distanceToCamera < b._distanceToCamera) {
  19021. return 1;
  19022. }
  19023. if (a._distanceToCamera > b._distanceToCamera) {
  19024. return -1;
  19025. }
  19026. return 0;
  19027. };
  19028. /**
  19029. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19030. * are rendered front to back (prevent overdraw).
  19031. *
  19032. * @param a The first submesh
  19033. * @param b The second submesh
  19034. * @returns The result of the comparison
  19035. */
  19036. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19037. // Then distance to camera
  19038. if (a._distanceToCamera < b._distanceToCamera) {
  19039. return -1;
  19040. }
  19041. if (a._distanceToCamera > b._distanceToCamera) {
  19042. return 1;
  19043. }
  19044. return 0;
  19045. };
  19046. /**
  19047. * Resets the different lists of submeshes to prepare a new frame.
  19048. */
  19049. RenderingGroup.prototype.prepare = function () {
  19050. this._opaqueSubMeshes.reset();
  19051. this._transparentSubMeshes.reset();
  19052. this._alphaTestSubMeshes.reset();
  19053. this._depthOnlySubMeshes.reset();
  19054. this._particleSystems.reset();
  19055. this._spriteManagers.reset();
  19056. this._edgesRenderers.reset();
  19057. };
  19058. RenderingGroup.prototype.dispose = function () {
  19059. this._opaqueSubMeshes.dispose();
  19060. this._transparentSubMeshes.dispose();
  19061. this._alphaTestSubMeshes.dispose();
  19062. this._depthOnlySubMeshes.dispose();
  19063. this._particleSystems.dispose();
  19064. this._spriteManagers.dispose();
  19065. this._edgesRenderers.dispose();
  19066. };
  19067. /**
  19068. * Inserts the submesh in its correct queue depending on its material.
  19069. * @param subMesh The submesh to dispatch
  19070. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19071. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19072. */
  19073. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19074. // Get mesh and materials if not provided
  19075. if (mesh === undefined) {
  19076. mesh = subMesh.getMesh();
  19077. }
  19078. if (material === undefined) {
  19079. material = subMesh.getMaterial();
  19080. }
  19081. if (material === null || material === undefined) {
  19082. return;
  19083. }
  19084. if (material.needAlphaBlendingForMesh(mesh)) {
  19085. this._transparentSubMeshes.push(subMesh);
  19086. }
  19087. else if (material.needAlphaTesting()) {
  19088. if (material.needDepthPrePass) {
  19089. this._depthOnlySubMeshes.push(subMesh);
  19090. }
  19091. this._alphaTestSubMeshes.push(subMesh);
  19092. }
  19093. else {
  19094. if (material.needDepthPrePass) {
  19095. this._depthOnlySubMeshes.push(subMesh);
  19096. }
  19097. this._opaqueSubMeshes.push(subMesh); // Opaque
  19098. }
  19099. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19100. this._edgesRenderers.push(mesh._edgesRenderer);
  19101. }
  19102. };
  19103. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19104. this._spriteManagers.push(spriteManager);
  19105. };
  19106. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19107. this._particleSystems.push(particleSystem);
  19108. };
  19109. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19110. if (this._particleSystems.length === 0) {
  19111. return;
  19112. }
  19113. // Particles
  19114. var activeCamera = this._scene.activeCamera;
  19115. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19116. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19117. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19118. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19119. continue;
  19120. }
  19121. var emitter = particleSystem.emitter;
  19122. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19123. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19124. }
  19125. }
  19126. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19127. };
  19128. RenderingGroup.prototype._renderSprites = function () {
  19129. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19130. return;
  19131. }
  19132. // Sprites
  19133. var activeCamera = this._scene.activeCamera;
  19134. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19135. for (var id = 0; id < this._spriteManagers.length; id++) {
  19136. var spriteManager = this._spriteManagers.data[id];
  19137. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19138. spriteManager.render();
  19139. }
  19140. }
  19141. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19142. };
  19143. return RenderingGroup;
  19144. }());
  19145. BABYLON.RenderingGroup = RenderingGroup;
  19146. })(BABYLON || (BABYLON = {}));
  19147. //# sourceMappingURL=babylon.renderingGroup.js.map
  19148. var BABYLON;
  19149. (function (BABYLON) {
  19150. var ClickInfo = /** @class */ (function () {
  19151. function ClickInfo() {
  19152. this._singleClick = false;
  19153. this._doubleClick = false;
  19154. this._hasSwiped = false;
  19155. this._ignore = false;
  19156. }
  19157. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19158. get: function () {
  19159. return this._singleClick;
  19160. },
  19161. set: function (b) {
  19162. this._singleClick = b;
  19163. },
  19164. enumerable: true,
  19165. configurable: true
  19166. });
  19167. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19168. get: function () {
  19169. return this._doubleClick;
  19170. },
  19171. set: function (b) {
  19172. this._doubleClick = b;
  19173. },
  19174. enumerable: true,
  19175. configurable: true
  19176. });
  19177. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19178. get: function () {
  19179. return this._hasSwiped;
  19180. },
  19181. set: function (b) {
  19182. this._hasSwiped = b;
  19183. },
  19184. enumerable: true,
  19185. configurable: true
  19186. });
  19187. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19188. get: function () {
  19189. return this._ignore;
  19190. },
  19191. set: function (b) {
  19192. this._ignore = b;
  19193. },
  19194. enumerable: true,
  19195. configurable: true
  19196. });
  19197. return ClickInfo;
  19198. }());
  19199. /**
  19200. * This class is used by the onRenderingGroupObservable
  19201. */
  19202. var RenderingGroupInfo = /** @class */ (function () {
  19203. function RenderingGroupInfo() {
  19204. }
  19205. /**
  19206. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19207. * This stage will be fired no matter what
  19208. */
  19209. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19210. /**
  19211. * Called before opaque object are rendered.
  19212. * This stage will be fired only if there's 3D Opaque content to render
  19213. */
  19214. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19215. /**
  19216. * Called after the opaque objects are rendered and before the transparent ones
  19217. * This stage will be fired only if there's 3D transparent content to render
  19218. */
  19219. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19220. /**
  19221. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19222. * This stage will be fired no matter what
  19223. */
  19224. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19225. return RenderingGroupInfo;
  19226. }());
  19227. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19228. /**
  19229. * Represents a scene to be rendered by the engine.
  19230. * @see http://doc.babylonjs.com/page.php?p=21911
  19231. */
  19232. var Scene = /** @class */ (function () {
  19233. /**
  19234. * @constructor
  19235. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19236. */
  19237. function Scene(engine) {
  19238. // Members
  19239. this.autoClear = true;
  19240. this.autoClearDepthAndStencil = true;
  19241. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19242. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19243. this.forceWireframe = false;
  19244. this._forcePointsCloud = false;
  19245. this.forceShowBoundingBoxes = false;
  19246. this.animationsEnabled = true;
  19247. this.useConstantAnimationDeltaTime = false;
  19248. this.constantlyUpdateMeshUnderPointer = false;
  19249. this.hoverCursor = "pointer";
  19250. this.defaultCursor = "";
  19251. /**
  19252. * This is used to call preventDefault() on pointer down
  19253. * in order to block unwanted artifacts like system double clicks
  19254. */
  19255. this.preventDefaultOnPointerDown = true;
  19256. // Metadata
  19257. this.metadata = null;
  19258. /**
  19259. * An event triggered when the scene is disposed.
  19260. * @type {BABYLON.Observable}
  19261. */
  19262. this.onDisposeObservable = new BABYLON.Observable();
  19263. /**
  19264. * An event triggered before rendering the scene (right after animations and physics)
  19265. * @type {BABYLON.Observable}
  19266. */
  19267. this.onBeforeRenderObservable = new BABYLON.Observable();
  19268. /**
  19269. * An event triggered after rendering the scene
  19270. * @type {BABYLON.Observable}
  19271. */
  19272. this.onAfterRenderObservable = new BABYLON.Observable();
  19273. /**
  19274. * An event triggered before animating the scene
  19275. * @type {BABYLON.Observable}
  19276. */
  19277. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered after animations processing
  19280. * @type {BABYLON.Observable}
  19281. */
  19282. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19283. /**
  19284. * An event triggered before draw calls are ready to be sent
  19285. * @type {BABYLON.Observable}
  19286. */
  19287. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19288. /**
  19289. * An event triggered after draw calls have been sent
  19290. * @type {BABYLON.Observable}
  19291. */
  19292. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19293. /**
  19294. * An event triggered when physic simulation is about to be run
  19295. * @type {BABYLON.Observable}
  19296. */
  19297. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19298. /**
  19299. * An event triggered when physic simulation has been done
  19300. * @type {BABYLON.Observable}
  19301. */
  19302. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19303. /**
  19304. * An event triggered when the scene is ready
  19305. * @type {BABYLON.Observable}
  19306. */
  19307. this.onReadyObservable = new BABYLON.Observable();
  19308. /**
  19309. * An event triggered before rendering a camera
  19310. * @type {BABYLON.Observable}
  19311. */
  19312. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19313. /**
  19314. * An event triggered after rendering a camera
  19315. * @type {BABYLON.Observable}
  19316. */
  19317. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19318. /**
  19319. * An event triggered when active meshes evaluation is about to start
  19320. * @type {BABYLON.Observable}
  19321. */
  19322. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19323. /**
  19324. * An event triggered when active meshes evaluation is done
  19325. * @type {BABYLON.Observable}
  19326. */
  19327. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19328. /**
  19329. * An event triggered when particles rendering is about to start
  19330. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19331. * @type {BABYLON.Observable}
  19332. */
  19333. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19334. /**
  19335. * An event triggered when particles rendering is done
  19336. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19337. * @type {BABYLON.Observable}
  19338. */
  19339. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19340. /**
  19341. * An event triggered when sprites rendering is about to start
  19342. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19343. * @type {BABYLON.Observable}
  19344. */
  19345. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19346. /**
  19347. * An event triggered when sprites rendering is done
  19348. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19349. * @type {BABYLON.Observable}
  19350. */
  19351. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19352. /**
  19353. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19354. * @type {BABYLON.Observable}
  19355. */
  19356. this.onDataLoadedObservable = new BABYLON.Observable();
  19357. /**
  19358. * An event triggered when a camera is created
  19359. * @type {BABYLON.Observable}
  19360. */
  19361. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19362. /**
  19363. * An event triggered when a camera is removed
  19364. * @type {BABYLON.Observable}
  19365. */
  19366. this.onCameraRemovedObservable = new BABYLON.Observable();
  19367. /**
  19368. * An event triggered when a light is created
  19369. * @type {BABYLON.Observable}
  19370. */
  19371. this.onNewLightAddedObservable = new BABYLON.Observable();
  19372. /**
  19373. * An event triggered when a light is removed
  19374. * @type {BABYLON.Observable}
  19375. */
  19376. this.onLightRemovedObservable = new BABYLON.Observable();
  19377. /**
  19378. * An event triggered when a geometry is created
  19379. * @type {BABYLON.Observable}
  19380. */
  19381. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19382. /**
  19383. * An event triggered when a geometry is removed
  19384. * @type {BABYLON.Observable}
  19385. */
  19386. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19387. /**
  19388. * An event triggered when a transform node is created
  19389. * @type {BABYLON.Observable}
  19390. */
  19391. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19392. /**
  19393. * An event triggered when a transform node is removed
  19394. * @type {BABYLON.Observable}
  19395. */
  19396. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19397. /**
  19398. * An event triggered when a mesh is created
  19399. * @type {BABYLON.Observable}
  19400. */
  19401. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19402. /**
  19403. * An event triggered when a mesh is removed
  19404. * @type {BABYLON.Observable}
  19405. */
  19406. this.onMeshRemovedObservable = new BABYLON.Observable();
  19407. /**
  19408. * An event triggered when render targets are about to be rendered
  19409. * Can happen multiple times per frame.
  19410. * @type {BABYLON.Observable}
  19411. */
  19412. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19413. /**
  19414. * An event triggered when render targets were rendered.
  19415. * Can happen multiple times per frame.
  19416. * @type {BABYLON.Observable}
  19417. */
  19418. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19419. /**
  19420. * An event triggered before calculating deterministic simulation step
  19421. * @type {BABYLON.Observable}
  19422. */
  19423. this.onBeforeStepObservable = new BABYLON.Observable();
  19424. /**
  19425. * An event triggered after calculating deterministic simulation step
  19426. * @type {BABYLON.Observable}
  19427. */
  19428. this.onAfterStepObservable = new BABYLON.Observable();
  19429. /**
  19430. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19431. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19432. * 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)
  19433. */
  19434. this.onRenderingGroupObservable = new BABYLON.Observable();
  19435. // Animations
  19436. this.animations = [];
  19437. /**
  19438. * 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).
  19439. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19440. */
  19441. this.onPrePointerObservable = new BABYLON.Observable();
  19442. /**
  19443. * Observable event triggered each time an input event is received from the rendering canvas
  19444. */
  19445. this.onPointerObservable = new BABYLON.Observable();
  19446. this._meshPickProceed = false;
  19447. this._currentPickResult = null;
  19448. this._previousPickResult = null;
  19449. this._totalPointersPressed = 0;
  19450. this._doubleClickOccured = false;
  19451. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19452. this.cameraToUseForPointers = null;
  19453. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19454. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19455. this._startingPointerTime = 0;
  19456. this._previousStartingPointerTime = 0;
  19457. // Deterministic lockstep
  19458. this._timeAccumulator = 0;
  19459. this._currentStepId = 0;
  19460. this._currentInternalStep = 0;
  19461. // Keyboard
  19462. /**
  19463. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19464. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19465. */
  19466. this.onPreKeyboardObservable = new BABYLON.Observable();
  19467. /**
  19468. * Observable event triggered each time an keyboard event is received from the hosting window
  19469. */
  19470. this.onKeyboardObservable = new BABYLON.Observable();
  19471. // Coordinate system
  19472. /**
  19473. * use right-handed coordinate system on this scene.
  19474. * @type {boolean}
  19475. */
  19476. this._useRightHandedSystem = false;
  19477. // Fog
  19478. this._fogEnabled = true;
  19479. this._fogMode = Scene.FOGMODE_NONE;
  19480. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19481. this.fogDensity = 0.1;
  19482. this.fogStart = 0;
  19483. this.fogEnd = 1000.0;
  19484. // Lights
  19485. /**
  19486. * is shadow enabled on this scene.
  19487. * @type {boolean}
  19488. */
  19489. this._shadowsEnabled = true;
  19490. /**
  19491. * is light enabled on this scene.
  19492. * @type {boolean}
  19493. */
  19494. this._lightsEnabled = true;
  19495. /**
  19496. * All of the lights added to this scene.
  19497. * @see BABYLON.Light
  19498. * @type {BABYLON.Light[]}
  19499. */
  19500. this.lights = new Array();
  19501. // Cameras
  19502. /** All of the cameras added to this scene. */
  19503. this.cameras = new Array();
  19504. /** All of the active cameras added to this scene. */
  19505. this.activeCameras = new Array();
  19506. // Meshes
  19507. /**
  19508. * All of the tranform nodes added to this scene.
  19509. * @see BABYLON.TransformNode
  19510. * @type {BABYLON.TransformNode[]}
  19511. */
  19512. this.transformNodes = new Array();
  19513. /**
  19514. * All of the (abstract) meshes added to this scene.
  19515. * @see BABYLON.AbstractMesh
  19516. * @type {BABYLON.AbstractMesh[]}
  19517. */
  19518. this.meshes = new Array();
  19519. /**
  19520. * All of the animation groups added to this scene.
  19521. * @see BABYLON.AnimationGroup
  19522. * @type {BABYLON.AnimationGroup[]}
  19523. */
  19524. this.animationGroups = new Array();
  19525. // Geometries
  19526. this._geometries = new Array();
  19527. this.materials = new Array();
  19528. this.multiMaterials = new Array();
  19529. // Textures
  19530. this._texturesEnabled = true;
  19531. this.textures = new Array();
  19532. // Particles
  19533. this.particlesEnabled = true;
  19534. this.particleSystems = new Array();
  19535. // Sprites
  19536. this.spritesEnabled = true;
  19537. this.spriteManagers = new Array();
  19538. // Layers
  19539. this.layers = new Array();
  19540. this.highlightLayers = new Array();
  19541. // Skeletons
  19542. this._skeletonsEnabled = true;
  19543. this.skeletons = new Array();
  19544. // Morph targets
  19545. this.morphTargetManagers = new Array();
  19546. // Lens flares
  19547. this.lensFlaresEnabled = true;
  19548. this.lensFlareSystems = new Array();
  19549. // Collisions
  19550. this.collisionsEnabled = true;
  19551. /** Defines the gravity applied to this scene */
  19552. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19553. // Postprocesses
  19554. this.postProcesses = new Array();
  19555. this.postProcessesEnabled = true;
  19556. // Customs render targets
  19557. this.renderTargetsEnabled = true;
  19558. this.dumpNextRenderTargets = false;
  19559. this.customRenderTargets = new Array();
  19560. // Imported meshes
  19561. this.importedMeshesFiles = new Array();
  19562. // Probes
  19563. this.probesEnabled = true;
  19564. this.reflectionProbes = new Array();
  19565. this._actionManagers = new Array();
  19566. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19567. // Procedural textures
  19568. this.proceduralTexturesEnabled = true;
  19569. this._proceduralTextures = new Array();
  19570. this.soundTracks = new Array();
  19571. this._audioEnabled = true;
  19572. this._headphone = false;
  19573. // Performance counters
  19574. this._totalVertices = new BABYLON.PerfCounter();
  19575. this._activeIndices = new BABYLON.PerfCounter();
  19576. this._activeParticles = new BABYLON.PerfCounter();
  19577. this._activeBones = new BABYLON.PerfCounter();
  19578. this._animationTime = 0;
  19579. this.animationTimeScale = 1;
  19580. this._renderId = 0;
  19581. this._executeWhenReadyTimeoutId = -1;
  19582. this._intermediateRendering = false;
  19583. this._viewUpdateFlag = -1;
  19584. this._projectionUpdateFlag = -1;
  19585. this._alternateViewUpdateFlag = -1;
  19586. this._alternateProjectionUpdateFlag = -1;
  19587. this._toBeDisposed = new BABYLON.SmartArray(256);
  19588. this._activeRequests = new Array();
  19589. this._pendingData = new Array();
  19590. this._isDisposed = false;
  19591. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19592. this._activeMeshes = new BABYLON.SmartArray(256);
  19593. this._processedMaterials = new BABYLON.SmartArray(256);
  19594. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19595. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19596. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19597. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19598. this._activeAnimatables = new Array();
  19599. this._transformMatrix = BABYLON.Matrix.Zero();
  19600. this._useAlternateCameraConfiguration = false;
  19601. this._alternateRendering = false;
  19602. this.requireLightSorting = false;
  19603. this._activeMeshesFrozen = false;
  19604. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19605. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19606. this._engine.scenes.push(this);
  19607. this._uid = null;
  19608. this._renderingManager = new BABYLON.RenderingManager(this);
  19609. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19610. if (BABYLON.OutlineRenderer) {
  19611. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19612. }
  19613. if (BABYLON.Tools.IsWindowObjectExist()) {
  19614. this.attachControl();
  19615. }
  19616. //simplification queue
  19617. if (BABYLON.SimplificationQueue) {
  19618. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19619. }
  19620. //collision coordinator initialization. For now legacy per default.
  19621. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19622. // Uniform Buffer
  19623. this._createUbo();
  19624. // Default Image processing definition.
  19625. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19626. }
  19627. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19628. /** The fog is deactivated */
  19629. get: function () {
  19630. return Scene._FOGMODE_NONE;
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19636. /** The fog density is following an exponential function */
  19637. get: function () {
  19638. return Scene._FOGMODE_EXP;
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19644. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19645. get: function () {
  19646. return Scene._FOGMODE_EXP2;
  19647. },
  19648. enumerable: true,
  19649. configurable: true
  19650. });
  19651. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19652. /** The fog density is following a linear function. */
  19653. get: function () {
  19654. return Scene._FOGMODE_LINEAR;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19660. /**
  19661. * Texture used in all pbr material as the reflection texture.
  19662. * As in the majority of the scene they are the same (exception for multi room and so on),
  19663. * this is easier to reference from here than from all the materials.
  19664. */
  19665. get: function () {
  19666. return this._environmentTexture;
  19667. },
  19668. /**
  19669. * Texture used in all pbr material as the reflection texture.
  19670. * As in the majority of the scene they are the same (exception for multi room and so on),
  19671. * this is easier to set here than in all the materials.
  19672. */
  19673. set: function (value) {
  19674. if (this._environmentTexture === value) {
  19675. return;
  19676. }
  19677. this._environmentTexture = value;
  19678. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19684. /**
  19685. * Default image processing configuration used either in the rendering
  19686. * Forward main pass or through the imageProcessingPostProcess if present.
  19687. * As in the majority of the scene they are the same (exception for multi camera),
  19688. * this is easier to reference from here than from all the materials and post process.
  19689. *
  19690. * No setter as we it is a shared configuration, you can set the values instead.
  19691. */
  19692. get: function () {
  19693. return this._imageProcessingConfiguration;
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19699. get: function () {
  19700. return this._forcePointsCloud;
  19701. },
  19702. set: function (value) {
  19703. if (this._forcePointsCloud === value) {
  19704. return;
  19705. }
  19706. this._forcePointsCloud = value;
  19707. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(Scene.prototype, "onDispose", {
  19713. /** A function to be executed when this scene is disposed. */
  19714. set: function (callback) {
  19715. if (this._onDisposeObserver) {
  19716. this.onDisposeObservable.remove(this._onDisposeObserver);
  19717. }
  19718. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(Scene.prototype, "beforeRender", {
  19724. /** A function to be executed before rendering this scene */
  19725. set: function (callback) {
  19726. if (this._onBeforeRenderObserver) {
  19727. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19728. }
  19729. if (callback) {
  19730. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19731. }
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(Scene.prototype, "afterRender", {
  19737. /** A function to be executed after rendering this scene */
  19738. set: function (callback) {
  19739. if (this._onAfterRenderObserver) {
  19740. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19741. }
  19742. if (callback) {
  19743. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19744. }
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19750. set: function (callback) {
  19751. if (this._onBeforeCameraRenderObserver) {
  19752. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19753. }
  19754. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19755. },
  19756. enumerable: true,
  19757. configurable: true
  19758. });
  19759. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19760. set: function (callback) {
  19761. if (this._onAfterCameraRenderObserver) {
  19762. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19763. }
  19764. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19770. get: function () {
  19771. if (!this._gamepadManager) {
  19772. this._gamepadManager = new BABYLON.GamepadManager(this);
  19773. }
  19774. return this._gamepadManager;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19780. get: function () {
  19781. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19787. get: function () {
  19788. return this._useRightHandedSystem;
  19789. },
  19790. set: function (value) {
  19791. if (this._useRightHandedSystem === value) {
  19792. return;
  19793. }
  19794. this._useRightHandedSystem = value;
  19795. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Scene.prototype.setStepId = function (newStepId) {
  19801. this._currentStepId = newStepId;
  19802. };
  19803. ;
  19804. Scene.prototype.getStepId = function () {
  19805. return this._currentStepId;
  19806. };
  19807. ;
  19808. Scene.prototype.getInternalStep = function () {
  19809. return this._currentInternalStep;
  19810. };
  19811. ;
  19812. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19813. get: function () {
  19814. return this._fogEnabled;
  19815. },
  19816. /**
  19817. * is fog enabled on this scene.
  19818. */
  19819. set: function (value) {
  19820. if (this._fogEnabled === value) {
  19821. return;
  19822. }
  19823. this._fogEnabled = value;
  19824. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Scene.prototype, "fogMode", {
  19830. get: function () {
  19831. return this._fogMode;
  19832. },
  19833. set: function (value) {
  19834. if (this._fogMode === value) {
  19835. return;
  19836. }
  19837. this._fogMode = value;
  19838. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19844. get: function () {
  19845. return this._shadowsEnabled;
  19846. },
  19847. set: function (value) {
  19848. if (this._shadowsEnabled === value) {
  19849. return;
  19850. }
  19851. this._shadowsEnabled = value;
  19852. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19858. get: function () {
  19859. return this._lightsEnabled;
  19860. },
  19861. set: function (value) {
  19862. if (this._lightsEnabled === value) {
  19863. return;
  19864. }
  19865. this._lightsEnabled = value;
  19866. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19872. /** The default material used on meshes when no material is affected */
  19873. get: function () {
  19874. if (!this._defaultMaterial) {
  19875. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19876. }
  19877. return this._defaultMaterial;
  19878. },
  19879. /** The default material used on meshes when no material is affected */
  19880. set: function (value) {
  19881. this._defaultMaterial = value;
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19887. get: function () {
  19888. return this._texturesEnabled;
  19889. },
  19890. set: function (value) {
  19891. if (this._texturesEnabled === value) {
  19892. return;
  19893. }
  19894. this._texturesEnabled = value;
  19895. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19901. get: function () {
  19902. return this._skeletonsEnabled;
  19903. },
  19904. set: function (value) {
  19905. if (this._skeletonsEnabled === value) {
  19906. return;
  19907. }
  19908. this._skeletonsEnabled = value;
  19909. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19915. get: function () {
  19916. if (!this._postProcessRenderPipelineManager) {
  19917. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19918. }
  19919. return this._postProcessRenderPipelineManager;
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19925. get: function () {
  19926. if (!this._mainSoundTrack) {
  19927. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19928. }
  19929. return this._mainSoundTrack;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19935. get: function () {
  19936. return this._alternateRendering;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19942. get: function () {
  19943. return this._frustumPlanes;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  19949. /**
  19950. * Gets the current geometry buffer associated to the scene.
  19951. */
  19952. get: function () {
  19953. return this._geometryBufferRenderer;
  19954. },
  19955. /**
  19956. * Sets the current geometry buffer for the scene.
  19957. */
  19958. set: function (geometryBufferRenderer) {
  19959. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  19960. this._geometryBufferRenderer = geometryBufferRenderer;
  19961. }
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(Scene.prototype, "debugLayer", {
  19967. // Properties
  19968. get: function () {
  19969. if (!this._debugLayer) {
  19970. this._debugLayer = new BABYLON.DebugLayer(this);
  19971. }
  19972. return this._debugLayer;
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19978. get: function () {
  19979. return this._workerCollisions;
  19980. },
  19981. set: function (enabled) {
  19982. if (!BABYLON.CollisionCoordinatorLegacy) {
  19983. return;
  19984. }
  19985. enabled = (enabled && !!Worker);
  19986. this._workerCollisions = enabled;
  19987. if (this.collisionCoordinator) {
  19988. this.collisionCoordinator.destroy();
  19989. }
  19990. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19991. this.collisionCoordinator.init(this);
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19997. get: function () {
  19998. return this._selectionOctree;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20004. /**
  20005. * The mesh that is currently under the pointer.
  20006. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20007. */
  20008. get: function () {
  20009. return this._pointerOverMesh;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(Scene.prototype, "pointerX", {
  20015. /**
  20016. * Current on-screen X position of the pointer
  20017. * @return {number} X position of the pointer
  20018. */
  20019. get: function () {
  20020. return this._pointerX;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Object.defineProperty(Scene.prototype, "pointerY", {
  20026. /**
  20027. * Current on-screen Y position of the pointer
  20028. * @return {number} Y position of the pointer
  20029. */
  20030. get: function () {
  20031. return this._pointerY;
  20032. },
  20033. enumerable: true,
  20034. configurable: true
  20035. });
  20036. Scene.prototype.getCachedMaterial = function () {
  20037. return this._cachedMaterial;
  20038. };
  20039. Scene.prototype.getCachedEffect = function () {
  20040. return this._cachedEffect;
  20041. };
  20042. Scene.prototype.getCachedVisibility = function () {
  20043. return this._cachedVisibility;
  20044. };
  20045. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20046. if (visibility === void 0) { visibility = 1; }
  20047. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20048. };
  20049. Scene.prototype.getBoundingBoxRenderer = function () {
  20050. if (!this._boundingBoxRenderer) {
  20051. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20052. }
  20053. return this._boundingBoxRenderer;
  20054. };
  20055. Scene.prototype.getOutlineRenderer = function () {
  20056. return this._outlineRenderer;
  20057. };
  20058. Scene.prototype.getEngine = function () {
  20059. return this._engine;
  20060. };
  20061. Scene.prototype.getTotalVertices = function () {
  20062. return this._totalVertices.current;
  20063. };
  20064. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20065. get: function () {
  20066. return this._totalVertices;
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Scene.prototype.getActiveIndices = function () {
  20072. return this._activeIndices.current;
  20073. };
  20074. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20075. get: function () {
  20076. return this._activeIndices;
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. Scene.prototype.getActiveParticles = function () {
  20082. return this._activeParticles.current;
  20083. };
  20084. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20085. get: function () {
  20086. return this._activeParticles;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Scene.prototype.getActiveBones = function () {
  20092. return this._activeBones.current;
  20093. };
  20094. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20095. get: function () {
  20096. return this._activeBones;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. // Stats
  20102. Scene.prototype.getInterFramePerfCounter = function () {
  20103. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20104. return 0;
  20105. };
  20106. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20107. get: function () {
  20108. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20109. return null;
  20110. },
  20111. enumerable: true,
  20112. configurable: true
  20113. });
  20114. Scene.prototype.getLastFrameDuration = function () {
  20115. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20116. return 0;
  20117. };
  20118. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20119. get: function () {
  20120. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20121. return null;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20127. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20128. return 0;
  20129. };
  20130. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20131. get: function () {
  20132. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20133. return null;
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. Scene.prototype.getActiveMeshes = function () {
  20139. return this._activeMeshes;
  20140. };
  20141. Scene.prototype.getRenderTargetsDuration = function () {
  20142. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20143. return 0;
  20144. };
  20145. Scene.prototype.getRenderDuration = function () {
  20146. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20147. return 0;
  20148. };
  20149. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20150. get: function () {
  20151. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20152. return null;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Scene.prototype.getParticlesDuration = function () {
  20158. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20159. return 0;
  20160. };
  20161. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20162. get: function () {
  20163. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20164. return null;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Scene.prototype.getSpritesDuration = function () {
  20170. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20171. return 0;
  20172. };
  20173. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20174. get: function () {
  20175. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20176. return null;
  20177. },
  20178. enumerable: true,
  20179. configurable: true
  20180. });
  20181. Scene.prototype.getAnimationRatio = function () {
  20182. return this._animationRatio;
  20183. };
  20184. Scene.prototype.getRenderId = function () {
  20185. return this._renderId;
  20186. };
  20187. Scene.prototype.incrementRenderId = function () {
  20188. this._renderId++;
  20189. };
  20190. Scene.prototype._updatePointerPosition = function (evt) {
  20191. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20192. if (!canvasRect) {
  20193. return;
  20194. }
  20195. this._pointerX = evt.clientX - canvasRect.left;
  20196. this._pointerY = evt.clientY - canvasRect.top;
  20197. this._unTranslatedPointerX = this._pointerX;
  20198. this._unTranslatedPointerY = this._pointerY;
  20199. };
  20200. Scene.prototype._createUbo = function () {
  20201. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20202. this._sceneUbo.addUniform("viewProjection", 16);
  20203. this._sceneUbo.addUniform("view", 16);
  20204. };
  20205. Scene.prototype._createAlternateUbo = function () {
  20206. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20207. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20208. this._alternateSceneUbo.addUniform("view", 16);
  20209. };
  20210. // Pointers handling
  20211. /**
  20212. * Use this method to simulate a pointer move on a mesh
  20213. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20214. */
  20215. Scene.prototype.simulatePointerMove = function (pickResult) {
  20216. var evt = new PointerEvent("pointermove");
  20217. return this._processPointerMove(pickResult, evt);
  20218. };
  20219. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20220. var canvas = this._engine.getRenderingCanvas();
  20221. if (!canvas) {
  20222. return this;
  20223. }
  20224. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20225. this.setPointerOverSprite(null);
  20226. this.setPointerOverMesh(pickResult.pickedMesh);
  20227. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20228. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20229. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20230. }
  20231. else {
  20232. canvas.style.cursor = this.hoverCursor;
  20233. }
  20234. }
  20235. else {
  20236. canvas.style.cursor = this.defaultCursor;
  20237. }
  20238. }
  20239. else {
  20240. this.setPointerOverMesh(null);
  20241. // Sprites
  20242. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20243. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20244. this.setPointerOverSprite(pickResult.pickedSprite);
  20245. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20246. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20247. }
  20248. else {
  20249. canvas.style.cursor = this.hoverCursor;
  20250. }
  20251. }
  20252. else {
  20253. this.setPointerOverSprite(null);
  20254. // Restore pointer
  20255. canvas.style.cursor = this.defaultCursor;
  20256. }
  20257. }
  20258. if (pickResult) {
  20259. if (this.onPointerMove) {
  20260. this.onPointerMove(evt, pickResult);
  20261. }
  20262. if (this.onPointerObservable.hasObservers()) {
  20263. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20264. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20265. this.onPointerObservable.notifyObservers(pi, type);
  20266. }
  20267. }
  20268. return this;
  20269. };
  20270. /**
  20271. * Use this method to simulate a pointer down on a mesh
  20272. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20273. */
  20274. Scene.prototype.simulatePointerDown = function (pickResult) {
  20275. var evt = new PointerEvent("pointerdown");
  20276. return this._processPointerDown(pickResult, evt);
  20277. };
  20278. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20279. var _this = this;
  20280. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20281. this._pickedDownMesh = pickResult.pickedMesh;
  20282. var actionManager = pickResult.pickedMesh.actionManager;
  20283. if (actionManager) {
  20284. if (actionManager.hasPickTriggers) {
  20285. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20286. switch (evt.button) {
  20287. case 0:
  20288. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20289. break;
  20290. case 1:
  20291. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20292. break;
  20293. case 2:
  20294. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20295. break;
  20296. }
  20297. }
  20298. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20299. window.setTimeout(function () {
  20300. 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);
  20301. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20302. if (_this._totalPointersPressed !== 0 &&
  20303. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20304. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20305. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20306. _this._startingPointerTime = 0;
  20307. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20308. }
  20309. }
  20310. }, Scene.LongPressDelay);
  20311. }
  20312. }
  20313. }
  20314. if (pickResult) {
  20315. if (this.onPointerDown) {
  20316. this.onPointerDown(evt, pickResult);
  20317. }
  20318. if (this.onPointerObservable.hasObservers()) {
  20319. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20320. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20321. this.onPointerObservable.notifyObservers(pi, type);
  20322. }
  20323. }
  20324. return this;
  20325. };
  20326. /**
  20327. * Use this method to simulate a pointer up on a mesh
  20328. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20329. */
  20330. Scene.prototype.simulatePointerUp = function (pickResult) {
  20331. var evt = new PointerEvent("pointerup");
  20332. var clickInfo = new ClickInfo();
  20333. clickInfo.singleClick = true;
  20334. clickInfo.ignore = true;
  20335. return this._processPointerUp(pickResult, evt, clickInfo);
  20336. };
  20337. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20338. if (pickResult && pickResult && pickResult.pickedMesh) {
  20339. this._pickedUpMesh = pickResult.pickedMesh;
  20340. if (this._pickedDownMesh === this._pickedUpMesh) {
  20341. if (this.onPointerPick) {
  20342. this.onPointerPick(evt, pickResult);
  20343. }
  20344. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20345. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20346. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20347. this.onPointerObservable.notifyObservers(pi, type);
  20348. }
  20349. }
  20350. if (pickResult.pickedMesh.actionManager) {
  20351. if (clickInfo.ignore) {
  20352. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20353. }
  20354. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20355. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20356. }
  20357. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20359. }
  20360. }
  20361. }
  20362. if (this._pickedDownMesh &&
  20363. this._pickedDownMesh.actionManager &&
  20364. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20365. this._pickedDownMesh !== this._pickedUpMesh) {
  20366. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20367. }
  20368. if (this.onPointerUp) {
  20369. this.onPointerUp(evt, pickResult);
  20370. }
  20371. if (this.onPointerObservable.hasObservers()) {
  20372. if (!clickInfo.ignore) {
  20373. if (!clickInfo.hasSwiped) {
  20374. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20375. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20376. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20377. this.onPointerObservable.notifyObservers(pi, type);
  20378. }
  20379. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20380. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20381. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20382. this.onPointerObservable.notifyObservers(pi, type);
  20383. }
  20384. }
  20385. }
  20386. else {
  20387. var type = BABYLON.PointerEventTypes.POINTERUP;
  20388. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20389. this.onPointerObservable.notifyObservers(pi, type);
  20390. }
  20391. }
  20392. return this;
  20393. };
  20394. /**
  20395. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20396. * @param attachUp defines if you want to attach events to pointerup
  20397. * @param attachDown defines if you want to attach events to pointerdown
  20398. * @param attachMove defines if you want to attach events to pointermove
  20399. */
  20400. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20401. var _this = this;
  20402. if (attachUp === void 0) { attachUp = true; }
  20403. if (attachDown === void 0) { attachDown = true; }
  20404. if (attachMove === void 0) { attachMove = true; }
  20405. this._initActionManager = function (act, clickInfo) {
  20406. if (!_this._meshPickProceed) {
  20407. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20408. _this._currentPickResult = pickResult;
  20409. if (pickResult) {
  20410. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20411. }
  20412. _this._meshPickProceed = true;
  20413. }
  20414. return act;
  20415. };
  20416. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20417. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20418. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20419. btn !== _this._previousButtonPressed) {
  20420. _this._doubleClickOccured = false;
  20421. clickInfo.singleClick = true;
  20422. clickInfo.ignore = false;
  20423. cb(clickInfo, _this._currentPickResult);
  20424. }
  20425. };
  20426. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20427. var clickInfo = new ClickInfo();
  20428. _this._currentPickResult = null;
  20429. var act = null;
  20430. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20431. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20432. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20433. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20434. act = _this._initActionManager(act, clickInfo);
  20435. if (act)
  20436. checkPicking = act.hasPickTriggers;
  20437. }
  20438. if (checkPicking) {
  20439. var btn = evt.button;
  20440. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20441. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20442. if (!clickInfo.hasSwiped) {
  20443. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20444. if (!checkSingleClickImmediately) {
  20445. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20446. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20447. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20448. act = _this._initActionManager(act, clickInfo);
  20449. if (act)
  20450. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20451. }
  20452. }
  20453. if (checkSingleClickImmediately) {
  20454. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20455. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20456. btn !== _this._previousButtonPressed) {
  20457. clickInfo.singleClick = true;
  20458. cb(clickInfo, _this._currentPickResult);
  20459. }
  20460. }
  20461. else {
  20462. // wait that no double click has been raised during the double click delay
  20463. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20464. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20465. }
  20466. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20467. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20468. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20469. act = _this._initActionManager(act, clickInfo);
  20470. if (act)
  20471. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20472. }
  20473. if (checkDoubleClick) {
  20474. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20475. if (btn === _this._previousButtonPressed &&
  20476. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20477. !_this._doubleClickOccured) {
  20478. // pointer has not moved for 2 clicks, it's a double click
  20479. if (!clickInfo.hasSwiped &&
  20480. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20481. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20482. _this._previousStartingPointerTime = 0;
  20483. _this._doubleClickOccured = true;
  20484. clickInfo.doubleClick = true;
  20485. clickInfo.ignore = false;
  20486. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20487. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20488. }
  20489. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20490. cb(clickInfo, _this._currentPickResult);
  20491. }
  20492. else {
  20493. _this._doubleClickOccured = false;
  20494. _this._previousStartingPointerTime = _this._startingPointerTime;
  20495. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20496. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20497. _this._previousButtonPressed = btn;
  20498. if (Scene.ExclusiveDoubleClickMode) {
  20499. if (_this._previousDelayedSimpleClickTimeout) {
  20500. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20501. }
  20502. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20503. cb(clickInfo, _this._previousPickResult);
  20504. }
  20505. else {
  20506. cb(clickInfo, _this._currentPickResult);
  20507. }
  20508. }
  20509. }
  20510. else {
  20511. _this._doubleClickOccured = false;
  20512. _this._previousStartingPointerTime = _this._startingPointerTime;
  20513. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20514. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20515. _this._previousButtonPressed = btn;
  20516. }
  20517. }
  20518. }
  20519. }
  20520. clickInfo.ignore = true;
  20521. cb(clickInfo, _this._currentPickResult);
  20522. };
  20523. this._spritePredicate = function (sprite) {
  20524. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20525. };
  20526. this._onPointerMove = function (evt) {
  20527. _this._updatePointerPosition(evt);
  20528. // PreObservable support
  20529. if (_this.onPrePointerObservable.hasObservers()) {
  20530. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20531. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20532. _this.onPrePointerObservable.notifyObservers(pi, type);
  20533. if (pi.skipOnPointerObservable) {
  20534. return;
  20535. }
  20536. }
  20537. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20538. return;
  20539. }
  20540. if (!_this.pointerMovePredicate) {
  20541. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20542. }
  20543. // Meshes
  20544. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20545. _this._processPointerMove(pickResult, evt);
  20546. };
  20547. this._onPointerDown = function (evt) {
  20548. _this._totalPointersPressed++;
  20549. _this._pickedDownMesh = null;
  20550. _this._meshPickProceed = false;
  20551. _this._updatePointerPosition(evt);
  20552. if (_this.preventDefaultOnPointerDown && canvas) {
  20553. evt.preventDefault();
  20554. canvas.focus();
  20555. }
  20556. // PreObservable support
  20557. if (_this.onPrePointerObservable.hasObservers()) {
  20558. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20559. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20560. _this.onPrePointerObservable.notifyObservers(pi, type);
  20561. if (pi.skipOnPointerObservable) {
  20562. return;
  20563. }
  20564. }
  20565. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20566. return;
  20567. }
  20568. _this._startingPointerPosition.x = _this._pointerX;
  20569. _this._startingPointerPosition.y = _this._pointerY;
  20570. _this._startingPointerTime = new Date().getTime();
  20571. if (!_this.pointerDownPredicate) {
  20572. _this.pointerDownPredicate = function (mesh) {
  20573. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20574. };
  20575. }
  20576. // Meshes
  20577. _this._pickedDownMesh = null;
  20578. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20579. _this._processPointerDown(pickResult, evt);
  20580. // Sprites
  20581. _this._pickedDownSprite = null;
  20582. if (_this.spriteManagers.length > 0) {
  20583. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20584. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20585. if (pickResult.pickedSprite.actionManager) {
  20586. _this._pickedDownSprite = pickResult.pickedSprite;
  20587. switch (evt.button) {
  20588. case 0:
  20589. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20590. break;
  20591. case 1:
  20592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20593. break;
  20594. case 2:
  20595. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20596. break;
  20597. }
  20598. if (pickResult.pickedSprite.actionManager) {
  20599. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20600. }
  20601. }
  20602. }
  20603. }
  20604. };
  20605. this._onPointerUp = function (evt) {
  20606. if (_this._totalPointersPressed === 0) {
  20607. return; // So we need to test it the pointer down was pressed before.
  20608. }
  20609. _this._totalPointersPressed--;
  20610. _this._pickedUpMesh = null;
  20611. _this._meshPickProceed = false;
  20612. _this._updatePointerPosition(evt);
  20613. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20614. // PreObservable support
  20615. if (_this.onPrePointerObservable.hasObservers()) {
  20616. if (!clickInfo.ignore) {
  20617. if (!clickInfo.hasSwiped) {
  20618. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20619. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20620. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20621. _this.onPrePointerObservable.notifyObservers(pi, type);
  20622. if (pi.skipOnPointerObservable) {
  20623. return;
  20624. }
  20625. }
  20626. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20627. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20628. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20629. _this.onPrePointerObservable.notifyObservers(pi, type);
  20630. if (pi.skipOnPointerObservable) {
  20631. return;
  20632. }
  20633. }
  20634. }
  20635. }
  20636. else {
  20637. var type = BABYLON.PointerEventTypes.POINTERUP;
  20638. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20639. _this.onPrePointerObservable.notifyObservers(pi, type);
  20640. if (pi.skipOnPointerObservable) {
  20641. return;
  20642. }
  20643. }
  20644. }
  20645. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20646. return;
  20647. }
  20648. if (!_this.pointerUpPredicate) {
  20649. _this.pointerUpPredicate = function (mesh) {
  20650. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20651. };
  20652. }
  20653. // Meshes
  20654. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20655. _this._initActionManager(null, clickInfo);
  20656. }
  20657. if (!pickResult) {
  20658. pickResult = _this._currentPickResult;
  20659. }
  20660. _this._processPointerUp(pickResult, evt, clickInfo);
  20661. // Sprites
  20662. if (_this.spriteManagers.length > 0) {
  20663. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20664. if (spritePickResult) {
  20665. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20666. if (spritePickResult.pickedSprite.actionManager) {
  20667. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20668. if (spritePickResult.pickedSprite.actionManager) {
  20669. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20670. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20671. }
  20672. }
  20673. }
  20674. }
  20675. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20676. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20677. }
  20678. }
  20679. }
  20680. _this._previousPickResult = _this._currentPickResult;
  20681. });
  20682. };
  20683. this._onKeyDown = function (evt) {
  20684. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20685. if (_this.onPreKeyboardObservable.hasObservers()) {
  20686. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20687. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20688. if (pi.skipOnPointerObservable) {
  20689. return;
  20690. }
  20691. }
  20692. if (_this.onKeyboardObservable.hasObservers()) {
  20693. var pi = new BABYLON.KeyboardInfo(type, evt);
  20694. _this.onKeyboardObservable.notifyObservers(pi, type);
  20695. }
  20696. if (_this.actionManager) {
  20697. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20698. }
  20699. };
  20700. this._onKeyUp = function (evt) {
  20701. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20702. if (_this.onPreKeyboardObservable.hasObservers()) {
  20703. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20704. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20705. if (pi.skipOnPointerObservable) {
  20706. return;
  20707. }
  20708. }
  20709. if (_this.onKeyboardObservable.hasObservers()) {
  20710. var pi = new BABYLON.KeyboardInfo(type, evt);
  20711. _this.onKeyboardObservable.notifyObservers(pi, type);
  20712. }
  20713. if (_this.actionManager) {
  20714. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20715. }
  20716. };
  20717. var engine = this.getEngine();
  20718. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20719. if (!canvas) {
  20720. return;
  20721. }
  20722. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20723. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20724. });
  20725. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20726. if (!canvas) {
  20727. return;
  20728. }
  20729. canvas.removeEventListener("keydown", _this._onKeyDown);
  20730. canvas.removeEventListener("keyup", _this._onKeyUp);
  20731. });
  20732. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20733. var canvas = this._engine.getRenderingCanvas();
  20734. if (!canvas) {
  20735. return;
  20736. }
  20737. if (attachMove) {
  20738. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20739. // Wheel
  20740. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20741. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20742. }
  20743. if (attachDown) {
  20744. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20745. }
  20746. if (attachUp) {
  20747. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20748. }
  20749. canvas.tabIndex = 1;
  20750. };
  20751. Scene.prototype.detachControl = function () {
  20752. var engine = this.getEngine();
  20753. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20754. var canvas = engine.getRenderingCanvas();
  20755. if (!canvas) {
  20756. return;
  20757. }
  20758. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20759. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20760. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20761. if (this._onCanvasBlurObserver) {
  20762. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20763. }
  20764. if (this._onCanvasFocusObserver) {
  20765. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20766. }
  20767. // Wheel
  20768. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20769. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20770. // Keyboard
  20771. canvas.removeEventListener("keydown", this._onKeyDown);
  20772. canvas.removeEventListener("keyup", this._onKeyUp);
  20773. // Observables
  20774. this.onKeyboardObservable.clear();
  20775. this.onPreKeyboardObservable.clear();
  20776. this.onPointerObservable.clear();
  20777. this.onPrePointerObservable.clear();
  20778. };
  20779. /**
  20780. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20781. * Delay loaded resources are not taking in account
  20782. * @return true if all required resources are ready
  20783. */
  20784. Scene.prototype.isReady = function () {
  20785. if (this._isDisposed) {
  20786. return false;
  20787. }
  20788. if (this._pendingData.length > 0) {
  20789. return false;
  20790. }
  20791. var index;
  20792. var engine = this.getEngine();
  20793. // Geometries
  20794. for (index = 0; index < this._geometries.length; index++) {
  20795. var geometry = this._geometries[index];
  20796. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20797. return false;
  20798. }
  20799. }
  20800. // Meshes
  20801. for (index = 0; index < this.meshes.length; index++) {
  20802. var mesh = this.meshes[index];
  20803. if (!mesh.isEnabled()) {
  20804. continue;
  20805. }
  20806. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20807. continue;
  20808. }
  20809. if (!mesh.isReady()) {
  20810. return false;
  20811. }
  20812. // Highlight layers
  20813. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20814. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20815. var layer = _a[_i];
  20816. if (!layer.hasMesh(mesh)) {
  20817. continue;
  20818. }
  20819. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20820. var subMesh = _c[_b];
  20821. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20822. return false;
  20823. }
  20824. }
  20825. }
  20826. }
  20827. return true;
  20828. };
  20829. Scene.prototype.resetCachedMaterial = function () {
  20830. this._cachedMaterial = null;
  20831. this._cachedEffect = null;
  20832. this._cachedVisibility = null;
  20833. };
  20834. Scene.prototype.registerBeforeRender = function (func) {
  20835. this.onBeforeRenderObservable.add(func);
  20836. };
  20837. Scene.prototype.unregisterBeforeRender = function (func) {
  20838. this.onBeforeRenderObservable.removeCallback(func);
  20839. };
  20840. Scene.prototype.registerAfterRender = function (func) {
  20841. this.onAfterRenderObservable.add(func);
  20842. };
  20843. Scene.prototype.unregisterAfterRender = function (func) {
  20844. this.onAfterRenderObservable.removeCallback(func);
  20845. };
  20846. Scene.prototype._executeOnceBeforeRender = function (func) {
  20847. var _this = this;
  20848. var execFunc = function () {
  20849. func();
  20850. setTimeout(function () {
  20851. _this.unregisterBeforeRender(execFunc);
  20852. });
  20853. };
  20854. this.registerBeforeRender(execFunc);
  20855. };
  20856. /**
  20857. * The provided function will run before render once and will be disposed afterwards.
  20858. * A timeout delay can be provided so that the function will be executed in N ms.
  20859. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20860. * @param func The function to be executed.
  20861. * @param timeout optional delay in ms
  20862. */
  20863. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20864. var _this = this;
  20865. if (timeout !== undefined) {
  20866. setTimeout(function () {
  20867. _this._executeOnceBeforeRender(func);
  20868. }, timeout);
  20869. }
  20870. else {
  20871. this._executeOnceBeforeRender(func);
  20872. }
  20873. };
  20874. Scene.prototype._addPendingData = function (data) {
  20875. this._pendingData.push(data);
  20876. };
  20877. Scene.prototype._removePendingData = function (data) {
  20878. var wasLoading = this.isLoading;
  20879. var index = this._pendingData.indexOf(data);
  20880. if (index !== -1) {
  20881. this._pendingData.splice(index, 1);
  20882. }
  20883. if (wasLoading && !this.isLoading) {
  20884. this.onDataLoadedObservable.notifyObservers(this);
  20885. }
  20886. };
  20887. Scene.prototype.getWaitingItemsCount = function () {
  20888. return this._pendingData.length;
  20889. };
  20890. Object.defineProperty(Scene.prototype, "isLoading", {
  20891. get: function () {
  20892. return this._pendingData.length > 0;
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. /**
  20898. * Registers a function to be executed when the scene is ready.
  20899. * @param {Function} func - the function to be executed.
  20900. */
  20901. Scene.prototype.executeWhenReady = function (func) {
  20902. var _this = this;
  20903. this.onReadyObservable.add(func);
  20904. if (this._executeWhenReadyTimeoutId !== -1) {
  20905. return;
  20906. }
  20907. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20908. _this._checkIsReady();
  20909. }, 150);
  20910. };
  20911. Scene.prototype._checkIsReady = function () {
  20912. var _this = this;
  20913. if (this.isReady()) {
  20914. this.onReadyObservable.notifyObservers(this);
  20915. this.onReadyObservable.clear();
  20916. this._executeWhenReadyTimeoutId = -1;
  20917. return;
  20918. }
  20919. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20920. _this._checkIsReady();
  20921. }, 150);
  20922. };
  20923. // Animations
  20924. /**
  20925. * Will start the animation sequence of a given target
  20926. * @param target - the target
  20927. * @param {number} from - from which frame should animation start
  20928. * @param {number} to - till which frame should animation run.
  20929. * @param {boolean} [loop] - should the animation loop
  20930. * @param {number} [speedRatio] - the speed in which to run the animation
  20931. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20932. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20933. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20934. * See BABYLON.Animatable
  20935. */
  20936. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20937. if (speedRatio === void 0) { speedRatio = 1.0; }
  20938. if (from > to && speedRatio > 0) {
  20939. speedRatio *= -1;
  20940. }
  20941. this.stopAnimation(target);
  20942. if (!animatable) {
  20943. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20944. }
  20945. // Local animations
  20946. if (target.animations) {
  20947. animatable.appendAnimations(target, target.animations);
  20948. }
  20949. // Children animations
  20950. if (target.getAnimatables) {
  20951. var animatables = target.getAnimatables();
  20952. for (var index = 0; index < animatables.length; index++) {
  20953. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20954. }
  20955. }
  20956. animatable.reset();
  20957. return animatable;
  20958. };
  20959. /**
  20960. * Begin a new animation on a given node
  20961. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20962. * @param {BABYLON.Animation[]} defines the list of animations to start
  20963. * @param {number} from defines the initial value
  20964. * @param {number} to defines the final value
  20965. * @param {boolean} loop defines if you want animation to loop (off by default)
  20966. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20967. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20968. * @returns the list of created animatables
  20969. */
  20970. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20971. if (speedRatio === undefined) {
  20972. speedRatio = 1.0;
  20973. }
  20974. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20975. return animatable;
  20976. };
  20977. /**
  20978. * Begin a new animation on a given node and its hierarchy
  20979. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20980. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  20981. * @param {BABYLON.Animation[]} defines the list of animations to start
  20982. * @param {number} from defines the initial value
  20983. * @param {number} to defines the final value
  20984. * @param {boolean} loop defines if you want animation to loop (off by default)
  20985. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20986. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20987. * @returns the list of animatables created for all nodes
  20988. */
  20989. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20990. var children = target.getDescendants(directDescendantsOnly);
  20991. var result = [];
  20992. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20993. var child = children_1[_i];
  20994. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20995. }
  20996. return result;
  20997. };
  20998. Scene.prototype.getAnimatableByTarget = function (target) {
  20999. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21000. if (this._activeAnimatables[index].target === target) {
  21001. return this._activeAnimatables[index];
  21002. }
  21003. }
  21004. return null;
  21005. };
  21006. Object.defineProperty(Scene.prototype, "animatables", {
  21007. get: function () {
  21008. return this._activeAnimatables;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. /**
  21014. * Will stop the animation of the given target
  21015. * @param target - the target
  21016. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21017. * @see beginAnimation
  21018. */
  21019. Scene.prototype.stopAnimation = function (target, animationName) {
  21020. var animatable = this.getAnimatableByTarget(target);
  21021. if (animatable) {
  21022. animatable.stop(animationName);
  21023. }
  21024. };
  21025. /**
  21026. * Stops and removes all animations that have been applied to the scene
  21027. */
  21028. Scene.prototype.stopAllAnimations = function () {
  21029. if (this._activeAnimatables) {
  21030. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21031. this._activeAnimatables[i].stop();
  21032. }
  21033. this._activeAnimatables = [];
  21034. }
  21035. };
  21036. Scene.prototype._animate = function () {
  21037. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21038. return;
  21039. }
  21040. // Getting time
  21041. var now = BABYLON.Tools.Now;
  21042. if (!this._animationTimeLast) {
  21043. if (this._pendingData.length > 0) {
  21044. return;
  21045. }
  21046. this._animationTimeLast = now;
  21047. }
  21048. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21049. this._animationTime += deltaTime;
  21050. this._animationTimeLast = now;
  21051. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21052. this._activeAnimatables[index]._animate(this._animationTime);
  21053. }
  21054. };
  21055. // Matrix
  21056. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21057. this._useAlternateCameraConfiguration = active;
  21058. };
  21059. Scene.prototype.getViewMatrix = function () {
  21060. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21061. };
  21062. Scene.prototype.getProjectionMatrix = function () {
  21063. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21064. };
  21065. Scene.prototype.getTransformMatrix = function () {
  21066. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21067. };
  21068. Scene.prototype.setTransformMatrix = function (view, projection) {
  21069. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21070. return;
  21071. }
  21072. this._viewUpdateFlag = view.updateFlag;
  21073. this._projectionUpdateFlag = projection.updateFlag;
  21074. this._viewMatrix = view;
  21075. this._projectionMatrix = projection;
  21076. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21077. // Update frustum
  21078. if (!this._frustumPlanes) {
  21079. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21080. }
  21081. else {
  21082. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21083. }
  21084. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21085. var otherCamera = this.activeCamera._alternateCamera;
  21086. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21087. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21088. }
  21089. if (this._sceneUbo.useUbo) {
  21090. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21091. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21092. this._sceneUbo.update();
  21093. }
  21094. };
  21095. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21096. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21097. return;
  21098. }
  21099. this._alternateViewUpdateFlag = view.updateFlag;
  21100. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21101. this._alternateViewMatrix = view;
  21102. this._alternateProjectionMatrix = projection;
  21103. if (!this._alternateTransformMatrix) {
  21104. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21105. }
  21106. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21107. if (!this._alternateSceneUbo) {
  21108. this._createAlternateUbo();
  21109. }
  21110. if (this._alternateSceneUbo.useUbo) {
  21111. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21112. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21113. this._alternateSceneUbo.update();
  21114. }
  21115. };
  21116. Scene.prototype.getSceneUniformBuffer = function () {
  21117. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21118. };
  21119. // Methods
  21120. Scene.prototype.getUniqueId = function () {
  21121. var result = Scene._uniqueIdCounter;
  21122. Scene._uniqueIdCounter++;
  21123. return result;
  21124. };
  21125. Scene.prototype.addMesh = function (newMesh) {
  21126. this.meshes.push(newMesh);
  21127. //notify the collision coordinator
  21128. if (this.collisionCoordinator) {
  21129. this.collisionCoordinator.onMeshAdded(newMesh);
  21130. }
  21131. newMesh._resyncLightSources();
  21132. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21133. };
  21134. Scene.prototype.removeMesh = function (toRemove) {
  21135. var index = this.meshes.indexOf(toRemove);
  21136. if (index !== -1) {
  21137. // Remove from the scene if mesh found
  21138. this.meshes.splice(index, 1);
  21139. }
  21140. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21141. return index;
  21142. };
  21143. Scene.prototype.addTransformNode = function (newTransformNode) {
  21144. this.transformNodes.push(newTransformNode);
  21145. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21146. };
  21147. Scene.prototype.removeTransformNode = function (toRemove) {
  21148. var index = this.transformNodes.indexOf(toRemove);
  21149. if (index !== -1) {
  21150. // Remove from the scene if found
  21151. this.transformNodes.splice(index, 1);
  21152. }
  21153. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21154. return index;
  21155. };
  21156. Scene.prototype.removeSkeleton = function (toRemove) {
  21157. var index = this.skeletons.indexOf(toRemove);
  21158. if (index !== -1) {
  21159. // Remove from the scene if found
  21160. this.skeletons.splice(index, 1);
  21161. }
  21162. return index;
  21163. };
  21164. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21165. var index = this.morphTargetManagers.indexOf(toRemove);
  21166. if (index !== -1) {
  21167. // Remove from the scene if found
  21168. this.morphTargetManagers.splice(index, 1);
  21169. }
  21170. return index;
  21171. };
  21172. Scene.prototype.removeLight = function (toRemove) {
  21173. var index = this.lights.indexOf(toRemove);
  21174. if (index !== -1) {
  21175. // Remove from meshes
  21176. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21177. var mesh = _a[_i];
  21178. mesh._removeLightSource(toRemove);
  21179. }
  21180. // Remove from the scene if mesh found
  21181. this.lights.splice(index, 1);
  21182. this.sortLightsByPriority();
  21183. }
  21184. this.onLightRemovedObservable.notifyObservers(toRemove);
  21185. return index;
  21186. };
  21187. Scene.prototype.removeCamera = function (toRemove) {
  21188. var index = this.cameras.indexOf(toRemove);
  21189. if (index !== -1) {
  21190. // Remove from the scene if mesh found
  21191. this.cameras.splice(index, 1);
  21192. }
  21193. // Remove from activeCameras
  21194. var index2 = this.activeCameras.indexOf(toRemove);
  21195. if (index2 !== -1) {
  21196. // Remove from the scene if mesh found
  21197. this.activeCameras.splice(index2, 1);
  21198. }
  21199. // Reset the activeCamera
  21200. if (this.activeCamera === toRemove) {
  21201. if (this.cameras.length > 0) {
  21202. this.activeCamera = this.cameras[0];
  21203. }
  21204. else {
  21205. this.activeCamera = null;
  21206. }
  21207. }
  21208. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21209. return index;
  21210. };
  21211. Scene.prototype.removeParticleSystem = function (toRemove) {
  21212. var index = this.particleSystems.indexOf(toRemove);
  21213. if (index !== -1) {
  21214. this.particleSystems.splice(index, 1);
  21215. }
  21216. return index;
  21217. };
  21218. ;
  21219. Scene.prototype.removeAnimation = function (toRemove) {
  21220. var index = this.animations.indexOf(toRemove);
  21221. if (index !== -1) {
  21222. this.animations.splice(index, 1);
  21223. }
  21224. return index;
  21225. };
  21226. ;
  21227. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21228. var index = this.multiMaterials.indexOf(toRemove);
  21229. if (index !== -1) {
  21230. this.multiMaterials.splice(index, 1);
  21231. }
  21232. return index;
  21233. };
  21234. ;
  21235. Scene.prototype.removeMaterial = function (toRemove) {
  21236. var index = this.materials.indexOf(toRemove);
  21237. if (index !== -1) {
  21238. this.materials.splice(index, 1);
  21239. }
  21240. return index;
  21241. };
  21242. ;
  21243. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21244. var index = this.lensFlareSystems.indexOf(toRemove);
  21245. if (index !== -1) {
  21246. this.lensFlareSystems.splice(index, 1);
  21247. }
  21248. return index;
  21249. };
  21250. ;
  21251. Scene.prototype.removeActionManager = function (toRemove) {
  21252. var index = this._actionManagers.indexOf(toRemove);
  21253. if (index !== -1) {
  21254. this._actionManagers.splice(index, 1);
  21255. }
  21256. return index;
  21257. };
  21258. ;
  21259. Scene.prototype.addLight = function (newLight) {
  21260. this.lights.push(newLight);
  21261. this.sortLightsByPriority();
  21262. // Add light to all meshes (To support if the light is removed and then readded)
  21263. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21264. var mesh = _a[_i];
  21265. if (mesh._lightSources.indexOf(newLight) === -1) {
  21266. mesh._lightSources.push(newLight);
  21267. mesh._resyncLightSources();
  21268. }
  21269. }
  21270. this.onNewLightAddedObservable.notifyObservers(newLight);
  21271. };
  21272. Scene.prototype.sortLightsByPriority = function () {
  21273. if (this.requireLightSorting) {
  21274. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21275. }
  21276. };
  21277. Scene.prototype.addCamera = function (newCamera) {
  21278. this.cameras.push(newCamera);
  21279. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21280. };
  21281. Scene.prototype.addSkeleton = function (newSkeleton) {
  21282. this.skeletons.push(newSkeleton);
  21283. };
  21284. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21285. this.particleSystems.push(newParticleSystem);
  21286. };
  21287. Scene.prototype.addAnimation = function (newAnimation) {
  21288. this.animations.push(newAnimation);
  21289. };
  21290. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21291. this.multiMaterials.push(newMultiMaterial);
  21292. };
  21293. Scene.prototype.addMaterial = function (newMaterial) {
  21294. this.materials.push(newMaterial);
  21295. };
  21296. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21297. this.morphTargetManagers.push(newMorphTargetManager);
  21298. };
  21299. Scene.prototype.addGeometry = function (newGeometrie) {
  21300. this._geometries.push(newGeometrie);
  21301. };
  21302. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21303. this.lensFlareSystems.push(newLensFlareSystem);
  21304. };
  21305. Scene.prototype.addActionManager = function (newActionManager) {
  21306. this._actionManagers.push(newActionManager);
  21307. };
  21308. /**
  21309. * Switch active camera
  21310. * @param {Camera} newCamera - new active camera
  21311. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21312. */
  21313. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21314. if (attachControl === void 0) { attachControl = true; }
  21315. var canvas = this._engine.getRenderingCanvas();
  21316. if (!canvas) {
  21317. return;
  21318. }
  21319. if (this.activeCamera) {
  21320. this.activeCamera.detachControl(canvas);
  21321. }
  21322. this.activeCamera = newCamera;
  21323. if (attachControl) {
  21324. newCamera.attachControl(canvas);
  21325. }
  21326. };
  21327. /**
  21328. * sets the active camera of the scene using its ID
  21329. * @param {string} id - the camera's ID
  21330. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21331. * @see activeCamera
  21332. */
  21333. Scene.prototype.setActiveCameraByID = function (id) {
  21334. var camera = this.getCameraByID(id);
  21335. if (camera) {
  21336. this.activeCamera = camera;
  21337. return camera;
  21338. }
  21339. return null;
  21340. };
  21341. /**
  21342. * sets the active camera of the scene using its name
  21343. * @param {string} name - the camera's name
  21344. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21345. * @see activeCamera
  21346. */
  21347. Scene.prototype.setActiveCameraByName = function (name) {
  21348. var camera = this.getCameraByName(name);
  21349. if (camera) {
  21350. this.activeCamera = camera;
  21351. return camera;
  21352. }
  21353. return null;
  21354. };
  21355. /**
  21356. * get an animation group using its name
  21357. * @param {string} the material's name
  21358. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21359. */
  21360. Scene.prototype.getAnimationGroupByName = function (name) {
  21361. for (var index = 0; index < this.animationGroups.length; index++) {
  21362. if (this.animationGroups[index].name === name) {
  21363. return this.animationGroups[index];
  21364. }
  21365. }
  21366. return null;
  21367. };
  21368. /**
  21369. * get a material using its id
  21370. * @param {string} the material's ID
  21371. * @return {BABYLON.Material|null} the material or null if none found.
  21372. */
  21373. Scene.prototype.getMaterialByID = function (id) {
  21374. for (var index = 0; index < this.materials.length; index++) {
  21375. if (this.materials[index].id === id) {
  21376. return this.materials[index];
  21377. }
  21378. }
  21379. return null;
  21380. };
  21381. /**
  21382. * get a material using its name
  21383. * @param {string} the material's name
  21384. * @return {BABYLON.Material|null} the material or null if none found.
  21385. */
  21386. Scene.prototype.getMaterialByName = function (name) {
  21387. for (var index = 0; index < this.materials.length; index++) {
  21388. if (this.materials[index].name === name) {
  21389. return this.materials[index];
  21390. }
  21391. }
  21392. return null;
  21393. };
  21394. Scene.prototype.getLensFlareSystemByName = function (name) {
  21395. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21396. if (this.lensFlareSystems[index].name === name) {
  21397. return this.lensFlareSystems[index];
  21398. }
  21399. }
  21400. return null;
  21401. };
  21402. Scene.prototype.getLensFlareSystemByID = function (id) {
  21403. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21404. if (this.lensFlareSystems[index].id === id) {
  21405. return this.lensFlareSystems[index];
  21406. }
  21407. }
  21408. return null;
  21409. };
  21410. Scene.prototype.getCameraByID = function (id) {
  21411. for (var index = 0; index < this.cameras.length; index++) {
  21412. if (this.cameras[index].id === id) {
  21413. return this.cameras[index];
  21414. }
  21415. }
  21416. return null;
  21417. };
  21418. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21419. for (var index = 0; index < this.cameras.length; index++) {
  21420. if (this.cameras[index].uniqueId === uniqueId) {
  21421. return this.cameras[index];
  21422. }
  21423. }
  21424. return null;
  21425. };
  21426. /**
  21427. * get a camera using its name
  21428. * @param {string} the camera's name
  21429. * @return {BABYLON.Camera|null} the camera or null if none found.
  21430. */
  21431. Scene.prototype.getCameraByName = function (name) {
  21432. for (var index = 0; index < this.cameras.length; index++) {
  21433. if (this.cameras[index].name === name) {
  21434. return this.cameras[index];
  21435. }
  21436. }
  21437. return null;
  21438. };
  21439. /**
  21440. * get a bone using its id
  21441. * @param {string} the bone's id
  21442. * @return {BABYLON.Bone|null} the bone or null if not found
  21443. */
  21444. Scene.prototype.getBoneByID = function (id) {
  21445. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21446. var skeleton = this.skeletons[skeletonIndex];
  21447. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21448. if (skeleton.bones[boneIndex].id === id) {
  21449. return skeleton.bones[boneIndex];
  21450. }
  21451. }
  21452. }
  21453. return null;
  21454. };
  21455. /**
  21456. * get a bone using its id
  21457. * @param {string} the bone's name
  21458. * @return {BABYLON.Bone|null} the bone or null if not found
  21459. */
  21460. Scene.prototype.getBoneByName = function (name) {
  21461. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21462. var skeleton = this.skeletons[skeletonIndex];
  21463. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21464. if (skeleton.bones[boneIndex].name === name) {
  21465. return skeleton.bones[boneIndex];
  21466. }
  21467. }
  21468. }
  21469. return null;
  21470. };
  21471. /**
  21472. * get a light node using its name
  21473. * @param {string} the light's name
  21474. * @return {BABYLON.Light|null} the light or null if none found.
  21475. */
  21476. Scene.prototype.getLightByName = function (name) {
  21477. for (var index = 0; index < this.lights.length; index++) {
  21478. if (this.lights[index].name === name) {
  21479. return this.lights[index];
  21480. }
  21481. }
  21482. return null;
  21483. };
  21484. /**
  21485. * get a light node using its ID
  21486. * @param {string} the light's id
  21487. * @return {BABYLON.Light|null} the light or null if none found.
  21488. */
  21489. Scene.prototype.getLightByID = function (id) {
  21490. for (var index = 0; index < this.lights.length; index++) {
  21491. if (this.lights[index].id === id) {
  21492. return this.lights[index];
  21493. }
  21494. }
  21495. return null;
  21496. };
  21497. /**
  21498. * get a light node using its scene-generated unique ID
  21499. * @param {number} the light's unique id
  21500. * @return {BABYLON.Light|null} the light or null if none found.
  21501. */
  21502. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21503. for (var index = 0; index < this.lights.length; index++) {
  21504. if (this.lights[index].uniqueId === uniqueId) {
  21505. return this.lights[index];
  21506. }
  21507. }
  21508. return null;
  21509. };
  21510. /**
  21511. * get a particle system by id
  21512. * @param id {number} the particle system id
  21513. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21514. */
  21515. Scene.prototype.getParticleSystemByID = function (id) {
  21516. for (var index = 0; index < this.particleSystems.length; index++) {
  21517. if (this.particleSystems[index].id === id) {
  21518. return this.particleSystems[index];
  21519. }
  21520. }
  21521. return null;
  21522. };
  21523. /**
  21524. * get a geometry using its ID
  21525. * @param {string} the geometry's id
  21526. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21527. */
  21528. Scene.prototype.getGeometryByID = function (id) {
  21529. for (var index = 0; index < this._geometries.length; index++) {
  21530. if (this._geometries[index].id === id) {
  21531. return this._geometries[index];
  21532. }
  21533. }
  21534. return null;
  21535. };
  21536. /**
  21537. * add a new geometry to this scene.
  21538. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21539. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21540. * @return {boolean} was the geometry added or not
  21541. */
  21542. Scene.prototype.pushGeometry = function (geometry, force) {
  21543. if (!force && this.getGeometryByID(geometry.id)) {
  21544. return false;
  21545. }
  21546. this._geometries.push(geometry);
  21547. //notify the collision coordinator
  21548. if (this.collisionCoordinator) {
  21549. this.collisionCoordinator.onGeometryAdded(geometry);
  21550. }
  21551. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21552. return true;
  21553. };
  21554. /**
  21555. * Removes an existing geometry
  21556. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21557. * @return {boolean} was the geometry removed or not
  21558. */
  21559. Scene.prototype.removeGeometry = function (geometry) {
  21560. var index = this._geometries.indexOf(geometry);
  21561. if (index > -1) {
  21562. this._geometries.splice(index, 1);
  21563. //notify the collision coordinator
  21564. if (this.collisionCoordinator) {
  21565. this.collisionCoordinator.onGeometryDeleted(geometry);
  21566. }
  21567. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21568. return true;
  21569. }
  21570. return false;
  21571. };
  21572. Scene.prototype.getGeometries = function () {
  21573. return this._geometries;
  21574. };
  21575. /**
  21576. * Get the first added mesh found of a given ID
  21577. * @param {string} id - the id to search for
  21578. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21579. */
  21580. Scene.prototype.getMeshByID = function (id) {
  21581. for (var index = 0; index < this.meshes.length; index++) {
  21582. if (this.meshes[index].id === id) {
  21583. return this.meshes[index];
  21584. }
  21585. }
  21586. return null;
  21587. };
  21588. Scene.prototype.getMeshesByID = function (id) {
  21589. return this.meshes.filter(function (m) {
  21590. return m.id === id;
  21591. });
  21592. };
  21593. /**
  21594. * Get the first added transform node found of a given ID
  21595. * @param {string} id - the id to search for
  21596. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21597. */
  21598. Scene.prototype.getTransformNodeByID = function (id) {
  21599. for (var index = 0; index < this.transformNodes.length; index++) {
  21600. if (this.transformNodes[index].id === id) {
  21601. return this.transformNodes[index];
  21602. }
  21603. }
  21604. return null;
  21605. };
  21606. Scene.prototype.getTransformNodesByID = function (id) {
  21607. return this.transformNodes.filter(function (m) {
  21608. return m.id === id;
  21609. });
  21610. };
  21611. /**
  21612. * Get a mesh with its auto-generated unique id
  21613. * @param {number} uniqueId - the unique id to search for
  21614. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21615. */
  21616. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21617. for (var index = 0; index < this.meshes.length; index++) {
  21618. if (this.meshes[index].uniqueId === uniqueId) {
  21619. return this.meshes[index];
  21620. }
  21621. }
  21622. return null;
  21623. };
  21624. /**
  21625. * Get a the last added mesh found of a given ID
  21626. * @param {string} id - the id to search for
  21627. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21628. */
  21629. Scene.prototype.getLastMeshByID = function (id) {
  21630. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21631. if (this.meshes[index].id === id) {
  21632. return this.meshes[index];
  21633. }
  21634. }
  21635. return null;
  21636. };
  21637. /**
  21638. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21639. * @param {string} id - the id to search for
  21640. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21641. */
  21642. Scene.prototype.getLastEntryByID = function (id) {
  21643. var index;
  21644. for (index = this.meshes.length - 1; index >= 0; index--) {
  21645. if (this.meshes[index].id === id) {
  21646. return this.meshes[index];
  21647. }
  21648. }
  21649. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21650. if (this.transformNodes[index].id === id) {
  21651. return this.transformNodes[index];
  21652. }
  21653. }
  21654. for (index = this.cameras.length - 1; index >= 0; index--) {
  21655. if (this.cameras[index].id === id) {
  21656. return this.cameras[index];
  21657. }
  21658. }
  21659. for (index = this.lights.length - 1; index >= 0; index--) {
  21660. if (this.lights[index].id === id) {
  21661. return this.lights[index];
  21662. }
  21663. }
  21664. return null;
  21665. };
  21666. Scene.prototype.getNodeByID = function (id) {
  21667. var mesh = this.getMeshByID(id);
  21668. if (mesh) {
  21669. return mesh;
  21670. }
  21671. var light = this.getLightByID(id);
  21672. if (light) {
  21673. return light;
  21674. }
  21675. var camera = this.getCameraByID(id);
  21676. if (camera) {
  21677. return camera;
  21678. }
  21679. var bone = this.getBoneByID(id);
  21680. return bone;
  21681. };
  21682. Scene.prototype.getNodeByName = function (name) {
  21683. var mesh = this.getMeshByName(name);
  21684. if (mesh) {
  21685. return mesh;
  21686. }
  21687. var light = this.getLightByName(name);
  21688. if (light) {
  21689. return light;
  21690. }
  21691. var camera = this.getCameraByName(name);
  21692. if (camera) {
  21693. return camera;
  21694. }
  21695. var bone = this.getBoneByName(name);
  21696. return bone;
  21697. };
  21698. Scene.prototype.getMeshByName = function (name) {
  21699. for (var index = 0; index < this.meshes.length; index++) {
  21700. if (this.meshes[index].name === name) {
  21701. return this.meshes[index];
  21702. }
  21703. }
  21704. return null;
  21705. };
  21706. Scene.prototype.getTransformNodeByName = function (name) {
  21707. for (var index = 0; index < this.transformNodes.length; index++) {
  21708. if (this.transformNodes[index].name === name) {
  21709. return this.transformNodes[index];
  21710. }
  21711. }
  21712. return null;
  21713. };
  21714. Scene.prototype.getSoundByName = function (name) {
  21715. var index;
  21716. if (BABYLON.AudioEngine) {
  21717. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21718. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21719. return this.mainSoundTrack.soundCollection[index];
  21720. }
  21721. }
  21722. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21723. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21724. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21725. return this.soundTracks[sdIndex].soundCollection[index];
  21726. }
  21727. }
  21728. }
  21729. }
  21730. return null;
  21731. };
  21732. Scene.prototype.getLastSkeletonByID = function (id) {
  21733. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21734. if (this.skeletons[index].id === id) {
  21735. return this.skeletons[index];
  21736. }
  21737. }
  21738. return null;
  21739. };
  21740. Scene.prototype.getSkeletonById = function (id) {
  21741. for (var index = 0; index < this.skeletons.length; index++) {
  21742. if (this.skeletons[index].id === id) {
  21743. return this.skeletons[index];
  21744. }
  21745. }
  21746. return null;
  21747. };
  21748. Scene.prototype.getSkeletonByName = function (name) {
  21749. for (var index = 0; index < this.skeletons.length; index++) {
  21750. if (this.skeletons[index].name === name) {
  21751. return this.skeletons[index];
  21752. }
  21753. }
  21754. return null;
  21755. };
  21756. Scene.prototype.getMorphTargetManagerById = function (id) {
  21757. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21758. if (this.morphTargetManagers[index].uniqueId === id) {
  21759. return this.morphTargetManagers[index];
  21760. }
  21761. }
  21762. return null;
  21763. };
  21764. Scene.prototype.isActiveMesh = function (mesh) {
  21765. return (this._activeMeshes.indexOf(mesh) !== -1);
  21766. };
  21767. /**
  21768. * Return a the first highlight layer of the scene with a given name.
  21769. * @param name The name of the highlight layer to look for.
  21770. * @return The highlight layer if found otherwise null.
  21771. */
  21772. Scene.prototype.getHighlightLayerByName = function (name) {
  21773. for (var index = 0; index < this.highlightLayers.length; index++) {
  21774. if (this.highlightLayers[index].name === name) {
  21775. return this.highlightLayers[index];
  21776. }
  21777. }
  21778. return null;
  21779. };
  21780. Object.defineProperty(Scene.prototype, "uid", {
  21781. /**
  21782. * Return a unique id as a string which can serve as an identifier for the scene
  21783. */
  21784. get: function () {
  21785. if (!this._uid) {
  21786. this._uid = BABYLON.Tools.RandomId();
  21787. }
  21788. return this._uid;
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. /**
  21794. * Add an externaly attached data from its key.
  21795. * This method call will fail and return false, if such key already exists.
  21796. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21797. * @param key the unique key that identifies the data
  21798. * @param data the data object to associate to the key for this Engine instance
  21799. * @return true if no such key were already present and the data was added successfully, false otherwise
  21800. */
  21801. Scene.prototype.addExternalData = function (key, data) {
  21802. if (!this._externalData) {
  21803. this._externalData = new BABYLON.StringDictionary();
  21804. }
  21805. return this._externalData.add(key, data);
  21806. };
  21807. /**
  21808. * Get an externaly attached data from its key
  21809. * @param key the unique key that identifies the data
  21810. * @return the associated data, if present (can be null), or undefined if not present
  21811. */
  21812. Scene.prototype.getExternalData = function (key) {
  21813. if (!this._externalData) {
  21814. return null;
  21815. }
  21816. return this._externalData.get(key);
  21817. };
  21818. /**
  21819. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21820. * @param key the unique key that identifies the data
  21821. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21822. * @return the associated data, can be null if the factory returned null.
  21823. */
  21824. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21825. if (!this._externalData) {
  21826. this._externalData = new BABYLON.StringDictionary();
  21827. }
  21828. return this._externalData.getOrAddWithFactory(key, factory);
  21829. };
  21830. /**
  21831. * Remove an externaly attached data from the Engine instance
  21832. * @param key the unique key that identifies the data
  21833. * @return true if the data was successfully removed, false if it doesn't exist
  21834. */
  21835. Scene.prototype.removeExternalData = function (key) {
  21836. return this._externalData.remove(key);
  21837. };
  21838. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21839. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21840. if (mesh.showSubMeshesBoundingBox) {
  21841. var boundingInfo = subMesh.getBoundingInfo();
  21842. if (boundingInfo !== null && boundingInfo !== undefined) {
  21843. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21844. }
  21845. }
  21846. var material = subMesh.getMaterial();
  21847. if (material !== null && material !== undefined) {
  21848. // Render targets
  21849. if (material.getRenderTargetTextures !== undefined) {
  21850. if (this._processedMaterials.indexOf(material) === -1) {
  21851. this._processedMaterials.push(material);
  21852. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21853. }
  21854. }
  21855. // Dispatch
  21856. this._activeIndices.addCount(subMesh.indexCount, false);
  21857. this._renderingManager.dispatch(subMesh, mesh, material);
  21858. }
  21859. }
  21860. };
  21861. Scene.prototype._isInIntermediateRendering = function () {
  21862. return this._intermediateRendering;
  21863. };
  21864. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21865. this._activeMeshCandidateProvider = provider;
  21866. };
  21867. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21868. return this._activeMeshCandidateProvider;
  21869. };
  21870. /**
  21871. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21872. */
  21873. Scene.prototype.freezeActiveMeshes = function () {
  21874. this._evaluateActiveMeshes();
  21875. this._activeMeshesFrozen = true;
  21876. return this;
  21877. };
  21878. /**
  21879. * Use this function to restart evaluating active meshes on every frame
  21880. */
  21881. Scene.prototype.unfreezeActiveMeshes = function () {
  21882. this._activeMeshesFrozen = false;
  21883. return this;
  21884. };
  21885. Scene.prototype._evaluateActiveMeshes = function () {
  21886. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21887. return;
  21888. }
  21889. if (!this.activeCamera) {
  21890. return;
  21891. }
  21892. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21893. this.activeCamera._activeMeshes.reset();
  21894. this._activeMeshes.reset();
  21895. this._renderingManager.reset();
  21896. this._processedMaterials.reset();
  21897. this._activeParticleSystems.reset();
  21898. this._activeSkeletons.reset();
  21899. this._softwareSkinnedMeshes.reset();
  21900. if (this._boundingBoxRenderer) {
  21901. this._boundingBoxRenderer.reset();
  21902. }
  21903. // Meshes
  21904. var meshes;
  21905. var len;
  21906. var checkIsEnabled = true;
  21907. // Determine mesh candidates
  21908. if (this._activeMeshCandidateProvider !== undefined) {
  21909. // Use _activeMeshCandidateProvider
  21910. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21911. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21912. if (meshes !== undefined) {
  21913. len = meshes.length;
  21914. }
  21915. else {
  21916. len = 0;
  21917. }
  21918. }
  21919. else if (this._selectionOctree !== undefined) {
  21920. // Octree
  21921. var selection = this._selectionOctree.select(this._frustumPlanes);
  21922. meshes = selection.data;
  21923. len = selection.length;
  21924. }
  21925. else {
  21926. // Full scene traversal
  21927. len = this.meshes.length;
  21928. meshes = this.meshes;
  21929. }
  21930. // Check each mesh
  21931. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21932. mesh = meshes[meshIndex];
  21933. if (mesh.isBlocked) {
  21934. continue;
  21935. }
  21936. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21937. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21938. continue;
  21939. }
  21940. mesh.computeWorldMatrix();
  21941. // Intersections
  21942. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21943. this._meshesForIntersections.pushNoDuplicate(mesh);
  21944. }
  21945. // Switch to current LOD
  21946. meshLOD = mesh.getLOD(this.activeCamera);
  21947. if (meshLOD === undefined || meshLOD === null) {
  21948. continue;
  21949. }
  21950. mesh._preActivate();
  21951. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21952. this._activeMeshes.push(mesh);
  21953. this.activeCamera._activeMeshes.push(mesh);
  21954. mesh._activate(this._renderId);
  21955. if (meshLOD !== mesh) {
  21956. meshLOD._activate(this._renderId);
  21957. }
  21958. this._activeMesh(mesh, meshLOD);
  21959. }
  21960. }
  21961. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21962. // Particle systems
  21963. if (this.particlesEnabled) {
  21964. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21965. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21966. var particleSystem = this.particleSystems[particleIndex];
  21967. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21968. continue;
  21969. }
  21970. var emitter = particleSystem.emitter;
  21971. if (!emitter.position || emitter.isEnabled()) {
  21972. this._activeParticleSystems.push(particleSystem);
  21973. particleSystem.animate();
  21974. this._renderingManager.dispatchParticles(particleSystem);
  21975. }
  21976. }
  21977. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21978. }
  21979. };
  21980. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21981. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21982. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21983. mesh.skeleton.prepare();
  21984. }
  21985. if (!mesh.computeBonesUsingShaders) {
  21986. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21987. }
  21988. }
  21989. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21990. var boundingInfo = sourceMesh.getBoundingInfo();
  21991. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21992. }
  21993. if (mesh !== undefined && mesh !== null
  21994. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21995. // Submeshes Octrees
  21996. var len;
  21997. var subMeshes;
  21998. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21999. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22000. len = intersections.length;
  22001. subMeshes = intersections.data;
  22002. }
  22003. else {
  22004. subMeshes = mesh.subMeshes;
  22005. len = subMeshes.length;
  22006. }
  22007. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22008. subMesh = subMeshes[subIndex];
  22009. this._evaluateSubMesh(subMesh, mesh);
  22010. }
  22011. }
  22012. };
  22013. Scene.prototype.updateTransformMatrix = function (force) {
  22014. if (!this.activeCamera) {
  22015. return;
  22016. }
  22017. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22018. };
  22019. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22020. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22021. };
  22022. Scene.prototype._renderForCamera = function (camera) {
  22023. if (camera && camera._skipRendering) {
  22024. return;
  22025. }
  22026. var engine = this._engine;
  22027. this.activeCamera = camera;
  22028. if (!this.activeCamera)
  22029. throw new Error("Active camera not set");
  22030. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22031. // Viewport
  22032. engine.setViewport(this.activeCamera.viewport);
  22033. // Camera
  22034. this.resetCachedMaterial();
  22035. this._renderId++;
  22036. this.activeCamera.update();
  22037. this.updateTransformMatrix();
  22038. if (camera._alternateCamera) {
  22039. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22040. this._alternateRendering = true;
  22041. }
  22042. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22043. // Meshes
  22044. this._evaluateActiveMeshes();
  22045. // Software skinning
  22046. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22047. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22048. mesh.applySkeleton(mesh.skeleton);
  22049. }
  22050. // Render targets
  22051. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22052. var needsRestoreFrameBuffer = false;
  22053. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22054. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22055. }
  22056. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22057. this._intermediateRendering = true;
  22058. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22059. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22060. var renderTarget = this._renderTargets.data[renderIndex];
  22061. if (renderTarget._shouldRender()) {
  22062. this._renderId++;
  22063. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22064. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22065. }
  22066. }
  22067. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22068. this._intermediateRendering = false;
  22069. this._renderId++;
  22070. needsRestoreFrameBuffer = true; // Restore back buffer
  22071. }
  22072. // Render HighlightLayer Texture
  22073. var stencilState = this._engine.getStencilBuffer();
  22074. var renderhighlights = false;
  22075. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22076. this._intermediateRendering = true;
  22077. for (var i = 0; i < this.highlightLayers.length; i++) {
  22078. var highlightLayer = this.highlightLayers[i];
  22079. if (highlightLayer.shouldRender() &&
  22080. (!highlightLayer.camera ||
  22081. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22082. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22083. renderhighlights = true;
  22084. var renderTarget = highlightLayer._mainTexture;
  22085. if (renderTarget._shouldRender()) {
  22086. this._renderId++;
  22087. renderTarget.render(false, false);
  22088. needsRestoreFrameBuffer = true;
  22089. }
  22090. }
  22091. }
  22092. this._intermediateRendering = false;
  22093. this._renderId++;
  22094. }
  22095. if (needsRestoreFrameBuffer) {
  22096. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22097. }
  22098. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22099. // Prepare Frame
  22100. this.postProcessManager._prepareFrame();
  22101. // Backgrounds
  22102. var layerIndex;
  22103. var layer;
  22104. if (this.layers.length) {
  22105. engine.setDepthBuffer(false);
  22106. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22107. layer = this.layers[layerIndex];
  22108. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22109. layer.render();
  22110. }
  22111. }
  22112. engine.setDepthBuffer(true);
  22113. }
  22114. // Activate HighlightLayer stencil
  22115. if (renderhighlights) {
  22116. this._engine.setStencilBuffer(true);
  22117. }
  22118. // Render
  22119. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22120. this._renderingManager.render(null, null, true, true);
  22121. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22122. // Restore HighlightLayer stencil
  22123. if (renderhighlights) {
  22124. this._engine.setStencilBuffer(stencilState);
  22125. }
  22126. // Bounding boxes
  22127. if (this._boundingBoxRenderer) {
  22128. this._boundingBoxRenderer.render();
  22129. }
  22130. // Lens flares
  22131. if (this.lensFlaresEnabled) {
  22132. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22133. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22134. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22135. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22136. lensFlareSystem.render();
  22137. }
  22138. }
  22139. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22140. }
  22141. // Foregrounds
  22142. if (this.layers.length) {
  22143. engine.setDepthBuffer(false);
  22144. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22145. layer = this.layers[layerIndex];
  22146. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22147. layer.render();
  22148. }
  22149. }
  22150. engine.setDepthBuffer(true);
  22151. }
  22152. // Highlight Layer
  22153. if (renderhighlights) {
  22154. engine.setDepthBuffer(false);
  22155. for (var i = 0; i < this.highlightLayers.length; i++) {
  22156. if (this.highlightLayers[i].shouldRender()) {
  22157. this.highlightLayers[i].render();
  22158. }
  22159. }
  22160. engine.setDepthBuffer(true);
  22161. }
  22162. // Finalize frame
  22163. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22164. // Reset some special arrays
  22165. this._renderTargets.reset();
  22166. this._alternateRendering = false;
  22167. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22168. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22169. };
  22170. Scene.prototype._processSubCameras = function (camera) {
  22171. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22172. this._renderForCamera(camera);
  22173. return;
  22174. }
  22175. // Update camera
  22176. if (this.activeCamera) {
  22177. this.activeCamera.update();
  22178. }
  22179. // rig cameras
  22180. for (var index = 0; index < camera._rigCameras.length; index++) {
  22181. this._renderForCamera(camera._rigCameras[index]);
  22182. }
  22183. this.activeCamera = camera;
  22184. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22185. };
  22186. Scene.prototype._checkIntersections = function () {
  22187. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22188. var sourceMesh = this._meshesForIntersections.data[index];
  22189. if (!sourceMesh.actionManager) {
  22190. continue;
  22191. }
  22192. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22193. var action = sourceMesh.actionManager.actions[actionIndex];
  22194. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22195. var parameters = action.getTriggerParameter();
  22196. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22197. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22198. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22199. if (areIntersecting && currentIntersectionInProgress === -1) {
  22200. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22201. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22202. sourceMesh._intersectionsInProgress.push(otherMesh);
  22203. }
  22204. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22205. sourceMesh._intersectionsInProgress.push(otherMesh);
  22206. }
  22207. }
  22208. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22209. //They intersected, and now they don't.
  22210. //is this trigger an exit trigger? execute an event.
  22211. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22212. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22213. }
  22214. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22215. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22216. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22217. }
  22218. }
  22219. }
  22220. }
  22221. }
  22222. };
  22223. Scene.prototype.render = function () {
  22224. if (this.isDisposed) {
  22225. return;
  22226. }
  22227. this._activeParticles.fetchNewFrame();
  22228. this._totalVertices.fetchNewFrame();
  22229. this._activeIndices.fetchNewFrame();
  22230. this._activeBones.fetchNewFrame();
  22231. this._meshesForIntersections.reset();
  22232. this.resetCachedMaterial();
  22233. this.onBeforeAnimationsObservable.notifyObservers(this);
  22234. // Actions
  22235. if (this.actionManager) {
  22236. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22237. }
  22238. //Simplification Queue
  22239. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22240. this.simplificationQueue.executeNext();
  22241. }
  22242. if (this._engine.isDeterministicLockStep()) {
  22243. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22244. var defaultFPS = (60.0 / 1000.0);
  22245. var defaultFrameTime = 1000 / 60; // frame time in MS
  22246. if (this._physicsEngine) {
  22247. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22248. }
  22249. var stepsTaken = 0;
  22250. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22251. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22252. internalSteps = Math.min(internalSteps, maxSubSteps);
  22253. do {
  22254. this.onBeforeStepObservable.notifyObservers(this);
  22255. // Animations
  22256. this._animationRatio = defaultFrameTime * defaultFPS;
  22257. this._animate();
  22258. this.onAfterAnimationsObservable.notifyObservers(this);
  22259. // Physics
  22260. if (this._physicsEngine) {
  22261. this.onBeforePhysicsObservable.notifyObservers(this);
  22262. this._physicsEngine._step(defaultFrameTime / 1000);
  22263. this.onAfterPhysicsObservable.notifyObservers(this);
  22264. }
  22265. this.onAfterStepObservable.notifyObservers(this);
  22266. this._currentStepId++;
  22267. stepsTaken++;
  22268. deltaTime -= defaultFrameTime;
  22269. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22270. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22271. }
  22272. else {
  22273. // Animations
  22274. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22275. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22276. this._animate();
  22277. this.onAfterAnimationsObservable.notifyObservers(this);
  22278. // Physics
  22279. if (this._physicsEngine) {
  22280. this.onBeforePhysicsObservable.notifyObservers(this);
  22281. this._physicsEngine._step(deltaTime / 1000.0);
  22282. this.onAfterPhysicsObservable.notifyObservers(this);
  22283. }
  22284. }
  22285. // update gamepad manager
  22286. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22287. this._gamepadManager._checkGamepadsStatus();
  22288. }
  22289. // Before render
  22290. this.onBeforeRenderObservable.notifyObservers(this);
  22291. // Customs render targets
  22292. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22293. var engine = this.getEngine();
  22294. var currentActiveCamera = this.activeCamera;
  22295. if (this.renderTargetsEnabled) {
  22296. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22297. this._intermediateRendering = true;
  22298. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22299. var renderTarget = this.customRenderTargets[customIndex];
  22300. if (renderTarget._shouldRender()) {
  22301. this._renderId++;
  22302. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22303. if (!this.activeCamera)
  22304. throw new Error("Active camera not set");
  22305. // Viewport
  22306. engine.setViewport(this.activeCamera.viewport);
  22307. // Camera
  22308. this.updateTransformMatrix();
  22309. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22310. }
  22311. }
  22312. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22313. this._intermediateRendering = false;
  22314. this._renderId++;
  22315. }
  22316. // Restore back buffer
  22317. if (this.customRenderTargets.length > 0) {
  22318. engine.restoreDefaultFramebuffer();
  22319. }
  22320. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22321. this.activeCamera = currentActiveCamera;
  22322. // Procedural textures
  22323. if (this.proceduralTexturesEnabled) {
  22324. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22325. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22326. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22327. if (proceduralTexture._shouldRender()) {
  22328. proceduralTexture.render();
  22329. }
  22330. }
  22331. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22332. }
  22333. // Clear
  22334. if (this.autoClearDepthAndStencil || this.autoClear) {
  22335. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22336. }
  22337. // Shadows
  22338. if (this.shadowsEnabled) {
  22339. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22340. var light = this.lights[lightIndex];
  22341. var shadowGenerator = light.getShadowGenerator();
  22342. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22343. var shadowMap = (shadowGenerator.getShadowMap());
  22344. if (this.textures.indexOf(shadowMap) !== -1) {
  22345. this._renderTargets.push(shadowMap);
  22346. }
  22347. }
  22348. }
  22349. }
  22350. // Depth renderer
  22351. if (this._depthRenderer) {
  22352. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22353. }
  22354. // Geometry renderer
  22355. if (this._geometryBufferRenderer) {
  22356. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22357. }
  22358. // RenderPipeline
  22359. if (this._postProcessRenderPipelineManager) {
  22360. this._postProcessRenderPipelineManager.update();
  22361. }
  22362. // Multi-cameras?
  22363. if (this.activeCameras.length > 0) {
  22364. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22365. if (cameraIndex > 0) {
  22366. this._engine.clear(null, false, true, true);
  22367. }
  22368. this._processSubCameras(this.activeCameras[cameraIndex]);
  22369. }
  22370. }
  22371. else {
  22372. if (!this.activeCamera) {
  22373. throw new Error("No camera defined");
  22374. }
  22375. this._processSubCameras(this.activeCamera);
  22376. }
  22377. // Intersection checks
  22378. this._checkIntersections();
  22379. // Update the audio listener attached to the camera
  22380. if (BABYLON.AudioEngine) {
  22381. this._updateAudioParameters();
  22382. }
  22383. // After render
  22384. if (this.afterRender) {
  22385. this.afterRender();
  22386. }
  22387. this.onAfterRenderObservable.notifyObservers(this);
  22388. // Cleaning
  22389. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22390. var data = this._toBeDisposed.data[index];
  22391. if (data) {
  22392. data.dispose();
  22393. }
  22394. this._toBeDisposed[index] = null;
  22395. }
  22396. this._toBeDisposed.reset();
  22397. if (this.dumpNextRenderTargets) {
  22398. this.dumpNextRenderTargets = false;
  22399. }
  22400. this._activeBones.addCount(0, true);
  22401. this._activeIndices.addCount(0, true);
  22402. this._activeParticles.addCount(0, true);
  22403. };
  22404. Scene.prototype._updateAudioParameters = function () {
  22405. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22406. return;
  22407. }
  22408. var listeningCamera;
  22409. var audioEngine = BABYLON.Engine.audioEngine;
  22410. if (this.activeCameras.length > 0) {
  22411. listeningCamera = this.activeCameras[0];
  22412. }
  22413. else {
  22414. listeningCamera = this.activeCamera;
  22415. }
  22416. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22417. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22418. // for VR cameras
  22419. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22420. listeningCamera = listeningCamera.rigCameras[0];
  22421. }
  22422. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22423. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22424. cameraDirection.normalize();
  22425. // To avoid some errors on GearVR
  22426. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22427. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22428. }
  22429. var i;
  22430. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22431. var sound = this.mainSoundTrack.soundCollection[i];
  22432. if (sound.useCustomAttenuation) {
  22433. sound.updateDistanceFromListener();
  22434. }
  22435. }
  22436. for (i = 0; i < this.soundTracks.length; i++) {
  22437. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22438. sound = this.soundTracks[i].soundCollection[j];
  22439. if (sound.useCustomAttenuation) {
  22440. sound.updateDistanceFromListener();
  22441. }
  22442. }
  22443. }
  22444. }
  22445. };
  22446. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22447. // Audio
  22448. get: function () {
  22449. return this._audioEnabled;
  22450. },
  22451. set: function (value) {
  22452. this._audioEnabled = value;
  22453. if (BABYLON.AudioEngine) {
  22454. if (this._audioEnabled) {
  22455. this._enableAudio();
  22456. }
  22457. else {
  22458. this._disableAudio();
  22459. }
  22460. }
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Scene.prototype._disableAudio = function () {
  22466. var i;
  22467. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22468. this.mainSoundTrack.soundCollection[i].pause();
  22469. }
  22470. for (i = 0; i < this.soundTracks.length; i++) {
  22471. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22472. this.soundTracks[i].soundCollection[j].pause();
  22473. }
  22474. }
  22475. };
  22476. Scene.prototype._enableAudio = function () {
  22477. var i;
  22478. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22479. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22480. this.mainSoundTrack.soundCollection[i].play();
  22481. }
  22482. }
  22483. for (i = 0; i < this.soundTracks.length; i++) {
  22484. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22485. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22486. this.soundTracks[i].soundCollection[j].play();
  22487. }
  22488. }
  22489. }
  22490. };
  22491. Object.defineProperty(Scene.prototype, "headphone", {
  22492. get: function () {
  22493. return this._headphone;
  22494. },
  22495. set: function (value) {
  22496. this._headphone = value;
  22497. if (BABYLON.AudioEngine) {
  22498. if (this._headphone) {
  22499. this._switchAudioModeForHeadphones();
  22500. }
  22501. else {
  22502. this._switchAudioModeForNormalSpeakers();
  22503. }
  22504. }
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Scene.prototype._switchAudioModeForHeadphones = function () {
  22510. this.mainSoundTrack.switchPanningModelToHRTF();
  22511. for (var i = 0; i < this.soundTracks.length; i++) {
  22512. this.soundTracks[i].switchPanningModelToHRTF();
  22513. }
  22514. };
  22515. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22516. this.mainSoundTrack.switchPanningModelToEqualPower();
  22517. for (var i = 0; i < this.soundTracks.length; i++) {
  22518. this.soundTracks[i].switchPanningModelToEqualPower();
  22519. }
  22520. };
  22521. Scene.prototype.enableDepthRenderer = function () {
  22522. if (this._depthRenderer) {
  22523. return this._depthRenderer;
  22524. }
  22525. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22526. return this._depthRenderer;
  22527. };
  22528. Scene.prototype.disableDepthRenderer = function () {
  22529. if (!this._depthRenderer) {
  22530. return;
  22531. }
  22532. this._depthRenderer.dispose();
  22533. this._depthRenderer = null;
  22534. };
  22535. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22536. if (ratio === void 0) { ratio = 1; }
  22537. if (this._geometryBufferRenderer) {
  22538. return this._geometryBufferRenderer;
  22539. }
  22540. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22541. if (!this._geometryBufferRenderer.isSupported) {
  22542. this._geometryBufferRenderer = null;
  22543. }
  22544. return this._geometryBufferRenderer;
  22545. };
  22546. Scene.prototype.disableGeometryBufferRenderer = function () {
  22547. if (!this._geometryBufferRenderer) {
  22548. return;
  22549. }
  22550. this._geometryBufferRenderer.dispose();
  22551. this._geometryBufferRenderer = null;
  22552. };
  22553. Scene.prototype.freezeMaterials = function () {
  22554. for (var i = 0; i < this.materials.length; i++) {
  22555. this.materials[i].freeze();
  22556. }
  22557. };
  22558. Scene.prototype.unfreezeMaterials = function () {
  22559. for (var i = 0; i < this.materials.length; i++) {
  22560. this.materials[i].unfreeze();
  22561. }
  22562. };
  22563. Scene.prototype.dispose = function () {
  22564. this.beforeRender = null;
  22565. this.afterRender = null;
  22566. this.skeletons = [];
  22567. this.morphTargetManagers = [];
  22568. this.importedMeshesFiles = new Array();
  22569. this.stopAllAnimations();
  22570. this.resetCachedMaterial();
  22571. if (this._depthRenderer) {
  22572. this._depthRenderer.dispose();
  22573. }
  22574. if (this._gamepadManager) {
  22575. this._gamepadManager.dispose();
  22576. this._gamepadManager = null;
  22577. }
  22578. // Smart arrays
  22579. if (this.activeCamera) {
  22580. this.activeCamera._activeMeshes.dispose();
  22581. this.activeCamera = null;
  22582. }
  22583. this._activeMeshes.dispose();
  22584. this._renderingManager.dispose();
  22585. this._processedMaterials.dispose();
  22586. this._activeParticleSystems.dispose();
  22587. this._activeSkeletons.dispose();
  22588. this._softwareSkinnedMeshes.dispose();
  22589. this._renderTargets.dispose();
  22590. if (this._boundingBoxRenderer) {
  22591. this._boundingBoxRenderer.dispose();
  22592. }
  22593. this._meshesForIntersections.dispose();
  22594. this._toBeDisposed.dispose();
  22595. // Abort active requests
  22596. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22597. var request = _a[_i];
  22598. request.abort();
  22599. }
  22600. // Debug layer
  22601. if (this._debugLayer) {
  22602. this._debugLayer.hide();
  22603. }
  22604. // Events
  22605. this.onDisposeObservable.notifyObservers(this);
  22606. this.onDisposeObservable.clear();
  22607. this.onBeforeRenderObservable.clear();
  22608. this.onAfterRenderObservable.clear();
  22609. this.OnBeforeRenderTargetsRenderObservable.clear();
  22610. this.OnAfterRenderTargetsRenderObservable.clear();
  22611. this.onAfterStepObservable.clear();
  22612. this.onBeforeStepObservable.clear();
  22613. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22614. this.onAfterActiveMeshesEvaluationObservable.clear();
  22615. this.onBeforeParticlesRenderingObservable.clear();
  22616. this.onAfterParticlesRenderingObservable.clear();
  22617. this.onBeforeSpritesRenderingObservable.clear();
  22618. this.onAfterSpritesRenderingObservable.clear();
  22619. this.onBeforeDrawPhaseObservable.clear();
  22620. this.onAfterDrawPhaseObservable.clear();
  22621. this.onBeforePhysicsObservable.clear();
  22622. this.onAfterPhysicsObservable.clear();
  22623. this.onBeforeAnimationsObservable.clear();
  22624. this.onAfterAnimationsObservable.clear();
  22625. this.onDataLoadedObservable.clear();
  22626. this.detachControl();
  22627. // Release sounds & sounds tracks
  22628. if (BABYLON.AudioEngine) {
  22629. this.disposeSounds();
  22630. }
  22631. // VR Helper
  22632. if (this.VRHelper) {
  22633. this.VRHelper.dispose();
  22634. }
  22635. // Detach cameras
  22636. var canvas = this._engine.getRenderingCanvas();
  22637. if (canvas) {
  22638. var index;
  22639. for (index = 0; index < this.cameras.length; index++) {
  22640. this.cameras[index].detachControl(canvas);
  22641. }
  22642. }
  22643. // Release animation groups
  22644. while (this.animationGroups.length) {
  22645. this.animationGroups[0].dispose();
  22646. }
  22647. // Release lights
  22648. while (this.lights.length) {
  22649. this.lights[0].dispose();
  22650. }
  22651. // Release meshes
  22652. while (this.meshes.length) {
  22653. this.meshes[0].dispose(true);
  22654. }
  22655. while (this.transformNodes.length) {
  22656. this.removeTransformNode(this.transformNodes[0]);
  22657. }
  22658. // Release cameras
  22659. while (this.cameras.length) {
  22660. this.cameras[0].dispose();
  22661. }
  22662. // Release materials
  22663. if (this.defaultMaterial) {
  22664. this.defaultMaterial.dispose();
  22665. }
  22666. while (this.multiMaterials.length) {
  22667. this.multiMaterials[0].dispose();
  22668. }
  22669. while (this.materials.length) {
  22670. this.materials[0].dispose();
  22671. }
  22672. // Release particles
  22673. while (this.particleSystems.length) {
  22674. this.particleSystems[0].dispose();
  22675. }
  22676. // Release sprites
  22677. while (this.spriteManagers.length) {
  22678. this.spriteManagers[0].dispose();
  22679. }
  22680. // Release postProcesses
  22681. while (this.postProcesses.length) {
  22682. this.postProcesses[0].dispose();
  22683. }
  22684. // Release layers
  22685. while (this.layers.length) {
  22686. this.layers[0].dispose();
  22687. }
  22688. while (this.highlightLayers.length) {
  22689. this.highlightLayers[0].dispose();
  22690. }
  22691. // Release textures
  22692. while (this.textures.length) {
  22693. this.textures[0].dispose();
  22694. }
  22695. // Release UBO
  22696. this._sceneUbo.dispose();
  22697. if (this._alternateSceneUbo) {
  22698. this._alternateSceneUbo.dispose();
  22699. }
  22700. // Post-processes
  22701. this.postProcessManager.dispose();
  22702. if (this._postProcessRenderPipelineManager) {
  22703. this._postProcessRenderPipelineManager.dispose();
  22704. }
  22705. // Physics
  22706. if (this._physicsEngine) {
  22707. this.disablePhysicsEngine();
  22708. }
  22709. // Remove from engine
  22710. index = this._engine.scenes.indexOf(this);
  22711. if (index > -1) {
  22712. this._engine.scenes.splice(index, 1);
  22713. }
  22714. this._engine.wipeCaches(true);
  22715. this._isDisposed = true;
  22716. };
  22717. Object.defineProperty(Scene.prototype, "isDisposed", {
  22718. get: function () {
  22719. return this._isDisposed;
  22720. },
  22721. enumerable: true,
  22722. configurable: true
  22723. });
  22724. // Release sounds & sounds tracks
  22725. Scene.prototype.disposeSounds = function () {
  22726. if (!this._mainSoundTrack) {
  22727. return;
  22728. }
  22729. this.mainSoundTrack.dispose();
  22730. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22731. this.soundTracks[scIndex].dispose();
  22732. }
  22733. };
  22734. // Octrees
  22735. Scene.prototype.getWorldExtends = function () {
  22736. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22737. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22738. for (var index = 0; index < this.meshes.length; index++) {
  22739. var mesh = this.meshes[index];
  22740. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22741. continue;
  22742. }
  22743. mesh.computeWorldMatrix(true);
  22744. var boundingInfo = mesh.getBoundingInfo();
  22745. var minBox = boundingInfo.boundingBox.minimumWorld;
  22746. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22747. BABYLON.Tools.CheckExtends(minBox, min, max);
  22748. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22749. }
  22750. return {
  22751. min: min,
  22752. max: max
  22753. };
  22754. };
  22755. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22756. if (maxCapacity === void 0) { maxCapacity = 64; }
  22757. if (maxDepth === void 0) { maxDepth = 2; }
  22758. if (!this._selectionOctree) {
  22759. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22760. }
  22761. var worldExtends = this.getWorldExtends();
  22762. // Update octree
  22763. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22764. return this._selectionOctree;
  22765. };
  22766. // Picking
  22767. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22768. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22769. var result = BABYLON.Ray.Zero();
  22770. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22771. return result;
  22772. };
  22773. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22774. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22775. var engine = this._engine;
  22776. if (!camera) {
  22777. if (!this.activeCamera)
  22778. throw new Error("Active camera not set");
  22779. camera = this.activeCamera;
  22780. }
  22781. var cameraViewport = camera.viewport;
  22782. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22783. // Moving coordinates to local viewport world
  22784. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22785. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22786. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22787. return this;
  22788. };
  22789. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22790. var result = BABYLON.Ray.Zero();
  22791. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22792. return result;
  22793. };
  22794. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22795. if (!BABYLON.PickingInfo) {
  22796. return this;
  22797. }
  22798. var engine = this._engine;
  22799. if (!camera) {
  22800. if (!this.activeCamera)
  22801. throw new Error("Active camera not set");
  22802. camera = this.activeCamera;
  22803. }
  22804. var cameraViewport = camera.viewport;
  22805. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22806. var identity = BABYLON.Matrix.Identity();
  22807. // Moving coordinates to local viewport world
  22808. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22809. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22810. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22811. return this;
  22812. };
  22813. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22814. if (!BABYLON.PickingInfo) {
  22815. return null;
  22816. }
  22817. var pickingInfo = null;
  22818. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22819. var mesh = this.meshes[meshIndex];
  22820. if (predicate) {
  22821. if (!predicate(mesh)) {
  22822. continue;
  22823. }
  22824. }
  22825. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22826. continue;
  22827. }
  22828. var world = mesh.getWorldMatrix();
  22829. var ray = rayFunction(world);
  22830. var result = mesh.intersects(ray, fastCheck);
  22831. if (!result || !result.hit)
  22832. continue;
  22833. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22834. continue;
  22835. pickingInfo = result;
  22836. if (fastCheck) {
  22837. break;
  22838. }
  22839. }
  22840. return pickingInfo || new BABYLON.PickingInfo();
  22841. };
  22842. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22843. if (!BABYLON.PickingInfo) {
  22844. return null;
  22845. }
  22846. var pickingInfos = new Array();
  22847. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22848. var mesh = this.meshes[meshIndex];
  22849. if (predicate) {
  22850. if (!predicate(mesh)) {
  22851. continue;
  22852. }
  22853. }
  22854. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22855. continue;
  22856. }
  22857. var world = mesh.getWorldMatrix();
  22858. var ray = rayFunction(world);
  22859. var result = mesh.intersects(ray, false);
  22860. if (!result || !result.hit)
  22861. continue;
  22862. pickingInfos.push(result);
  22863. }
  22864. return pickingInfos;
  22865. };
  22866. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22867. if (!BABYLON.PickingInfo) {
  22868. return null;
  22869. }
  22870. var pickingInfo = null;
  22871. if (!camera) {
  22872. if (!this.activeCamera) {
  22873. return null;
  22874. }
  22875. camera = this.activeCamera;
  22876. }
  22877. if (this.spriteManagers.length > 0) {
  22878. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22879. var spriteManager = this.spriteManagers[spriteIndex];
  22880. if (!spriteManager.isPickable) {
  22881. continue;
  22882. }
  22883. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22884. if (!result || !result.hit)
  22885. continue;
  22886. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22887. continue;
  22888. pickingInfo = result;
  22889. if (fastCheck) {
  22890. break;
  22891. }
  22892. }
  22893. }
  22894. return pickingInfo || new BABYLON.PickingInfo();
  22895. };
  22896. /** Launch a ray to try to pick a mesh in the scene
  22897. * @param x position on screen
  22898. * @param y position on screen
  22899. * @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
  22900. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22901. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22902. */
  22903. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22904. var _this = this;
  22905. if (!BABYLON.PickingInfo) {
  22906. return null;
  22907. }
  22908. return this._internalPick(function (world) {
  22909. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22910. return _this._tempPickingRay;
  22911. }, predicate, fastCheck);
  22912. };
  22913. /** Launch a ray to try to pick a sprite in the scene
  22914. * @param x position on screen
  22915. * @param y position on screen
  22916. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  22917. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22918. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22919. */
  22920. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22921. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22922. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22923. };
  22924. /** Use the given ray to pick a mesh in the scene
  22925. * @param ray The ray to use to pick meshes
  22926. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  22927. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22928. */
  22929. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22930. var _this = this;
  22931. return this._internalPick(function (world) {
  22932. if (!_this._pickWithRayInverseMatrix) {
  22933. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22934. }
  22935. world.invertToRef(_this._pickWithRayInverseMatrix);
  22936. if (!_this._cachedRayForTransform) {
  22937. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22938. }
  22939. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22940. return _this._cachedRayForTransform;
  22941. }, predicate, fastCheck);
  22942. };
  22943. /**
  22944. * Launch a ray to try to pick a mesh in the scene
  22945. * @param x X position on screen
  22946. * @param y Y position on screen
  22947. * @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
  22948. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22949. */
  22950. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22951. var _this = this;
  22952. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22953. };
  22954. /**
  22955. * Launch a ray to try to pick a mesh in the scene
  22956. * @param ray Ray to use
  22957. * @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
  22958. */
  22959. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22960. var _this = this;
  22961. return this._internalMultiPick(function (world) {
  22962. if (!_this._pickWithRayInverseMatrix) {
  22963. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22964. }
  22965. world.invertToRef(_this._pickWithRayInverseMatrix);
  22966. if (!_this._cachedRayForTransform) {
  22967. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22968. }
  22969. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22970. return _this._cachedRayForTransform;
  22971. }, predicate);
  22972. };
  22973. Scene.prototype.setPointerOverMesh = function (mesh) {
  22974. if (this._pointerOverMesh === mesh) {
  22975. return;
  22976. }
  22977. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22978. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22979. }
  22980. this._pointerOverMesh = mesh;
  22981. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22982. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22983. }
  22984. };
  22985. Scene.prototype.getPointerOverMesh = function () {
  22986. return this._pointerOverMesh;
  22987. };
  22988. Scene.prototype.setPointerOverSprite = function (sprite) {
  22989. if (this._pointerOverSprite === sprite) {
  22990. return;
  22991. }
  22992. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22993. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22994. }
  22995. this._pointerOverSprite = sprite;
  22996. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22997. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22998. }
  22999. };
  23000. Scene.prototype.getPointerOverSprite = function () {
  23001. return this._pointerOverSprite;
  23002. };
  23003. // Physics
  23004. Scene.prototype.getPhysicsEngine = function () {
  23005. return this._physicsEngine;
  23006. };
  23007. /**
  23008. * Enables physics to the current scene
  23009. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23010. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23011. * @return {boolean} was the physics engine initialized
  23012. */
  23013. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23014. if (gravity === void 0) { gravity = null; }
  23015. if (this._physicsEngine) {
  23016. return true;
  23017. }
  23018. try {
  23019. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23020. return true;
  23021. }
  23022. catch (e) {
  23023. BABYLON.Tools.Error(e.message);
  23024. return false;
  23025. }
  23026. };
  23027. Scene.prototype.disablePhysicsEngine = function () {
  23028. if (!this._physicsEngine) {
  23029. return;
  23030. }
  23031. this._physicsEngine.dispose();
  23032. this._physicsEngine = null;
  23033. };
  23034. Scene.prototype.isPhysicsEnabled = function () {
  23035. return this._physicsEngine !== undefined;
  23036. };
  23037. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23038. var mesh = compound.parts[0].mesh;
  23039. if (mesh.physicsImpostor) {
  23040. mesh.physicsImpostor.dispose();
  23041. mesh.physicsImpostor = null;
  23042. }
  23043. };
  23044. // Misc.
  23045. Scene.prototype._rebuildGeometries = function () {
  23046. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23047. var geometry = _a[_i];
  23048. geometry._rebuild();
  23049. }
  23050. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23051. var mesh = _c[_b];
  23052. mesh._rebuild();
  23053. }
  23054. if (this.postProcessManager) {
  23055. this.postProcessManager._rebuild();
  23056. }
  23057. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23058. var layer = _e[_d];
  23059. layer._rebuild();
  23060. }
  23061. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23062. var highlightLayer = _g[_f];
  23063. highlightLayer._rebuild();
  23064. }
  23065. if (this._boundingBoxRenderer) {
  23066. this._boundingBoxRenderer._rebuild();
  23067. }
  23068. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23069. var system = _j[_h];
  23070. system.rebuild();
  23071. }
  23072. if (this._postProcessRenderPipelineManager) {
  23073. this._postProcessRenderPipelineManager._rebuild();
  23074. }
  23075. };
  23076. Scene.prototype._rebuildTextures = function () {
  23077. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23078. var texture = _a[_i];
  23079. texture._rebuild();
  23080. }
  23081. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23082. };
  23083. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23084. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23085. if (replace === void 0) { replace = false; }
  23086. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23087. // Dispose existing camera or light in replace mode.
  23088. if (replace) {
  23089. if (this.activeCamera) {
  23090. this.activeCamera.dispose();
  23091. this.activeCamera = null;
  23092. }
  23093. if (this.lights) {
  23094. for (var i = 0; i < this.lights.length; i++) {
  23095. this.lights[i].dispose();
  23096. }
  23097. }
  23098. }
  23099. // Light
  23100. if (this.lights.length === 0) {
  23101. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23102. }
  23103. // Camera
  23104. if (!this.activeCamera) {
  23105. var worldExtends = this.getWorldExtends();
  23106. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23107. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23108. var camera;
  23109. var radius = worldSize.length() * 1.5;
  23110. if (createArcRotateCamera) {
  23111. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23112. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23113. arcRotateCamera.wheelPrecision = 100 / radius;
  23114. camera = arcRotateCamera;
  23115. }
  23116. else {
  23117. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23118. freeCamera.setTarget(worldCenter);
  23119. camera = freeCamera;
  23120. }
  23121. camera.minZ = radius * 0.01;
  23122. camera.maxZ = radius * 1000;
  23123. camera.speed = radius * 0.2;
  23124. this.activeCamera = camera;
  23125. var canvas = this.getEngine().getRenderingCanvas();
  23126. if (attachCameraControls && canvas) {
  23127. camera.attachControl(canvas);
  23128. }
  23129. }
  23130. };
  23131. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23132. if (pbr === void 0) { pbr = false; }
  23133. if (scale === void 0) { scale = 1000; }
  23134. if (blur === void 0) { blur = 0; }
  23135. if (environmentTexture) {
  23136. this.environmentTexture = environmentTexture;
  23137. }
  23138. if (!this.environmentTexture) {
  23139. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23140. return null;
  23141. }
  23142. // Skybox
  23143. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23144. if (pbr) {
  23145. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23146. hdrSkyboxMaterial.backFaceCulling = false;
  23147. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23148. if (hdrSkyboxMaterial.reflectionTexture) {
  23149. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23150. }
  23151. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23152. hdrSkyboxMaterial.disableLighting = true;
  23153. hdrSkyboxMaterial.twoSidedLighting = true;
  23154. hdrSkybox.infiniteDistance = true;
  23155. hdrSkybox.material = hdrSkyboxMaterial;
  23156. }
  23157. else {
  23158. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23159. skyboxMaterial.backFaceCulling = false;
  23160. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23161. if (skyboxMaterial.reflectionTexture) {
  23162. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23163. }
  23164. skyboxMaterial.disableLighting = true;
  23165. hdrSkybox.infiniteDistance = true;
  23166. hdrSkybox.material = skyboxMaterial;
  23167. }
  23168. return hdrSkybox;
  23169. };
  23170. Scene.prototype.createDefaultEnvironment = function (options) {
  23171. if (BABYLON.EnvironmentHelper) {
  23172. return new BABYLON.EnvironmentHelper(options, this);
  23173. }
  23174. return null;
  23175. };
  23176. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23177. if (webVROptions === void 0) { webVROptions = {}; }
  23178. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23179. };
  23180. // Tags
  23181. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23182. if (tagsQuery === undefined) {
  23183. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23184. return list;
  23185. }
  23186. var listByTags = [];
  23187. forEach = forEach || (function (item) { return; });
  23188. for (var i in list) {
  23189. var item = list[i];
  23190. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23191. listByTags.push(item);
  23192. forEach(item);
  23193. }
  23194. }
  23195. return listByTags;
  23196. };
  23197. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23198. return this._getByTags(this.meshes, tagsQuery, forEach);
  23199. };
  23200. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23201. return this._getByTags(this.cameras, tagsQuery, forEach);
  23202. };
  23203. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23204. return this._getByTags(this.lights, tagsQuery, forEach);
  23205. };
  23206. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23207. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23208. };
  23209. /**
  23210. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23211. * This allowed control for front to back rendering or reversly depending of the special needs.
  23212. *
  23213. * @param renderingGroupId The rendering group id corresponding to its index
  23214. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23215. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23216. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23217. */
  23218. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23219. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23220. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23221. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23222. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23223. };
  23224. /**
  23225. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23226. *
  23227. * @param renderingGroupId The rendering group id corresponding to its index
  23228. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23229. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23230. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23231. */
  23232. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23233. if (depth === void 0) { depth = true; }
  23234. if (stencil === void 0) { stencil = true; }
  23235. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23236. };
  23237. /**
  23238. * Will flag all materials as dirty to trigger new shader compilation
  23239. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23240. */
  23241. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23242. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23243. var material = _a[_i];
  23244. if (predicate && !predicate(material)) {
  23245. continue;
  23246. }
  23247. material.markAsDirty(flag);
  23248. }
  23249. };
  23250. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23251. var _this = this;
  23252. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23253. this._activeRequests.push(request);
  23254. request.onCompleteObservable.add(function (request) {
  23255. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23256. });
  23257. return request;
  23258. };
  23259. // Statics
  23260. Scene._FOGMODE_NONE = 0;
  23261. Scene._FOGMODE_EXP = 1;
  23262. Scene._FOGMODE_EXP2 = 2;
  23263. Scene._FOGMODE_LINEAR = 3;
  23264. Scene._uniqueIdCounter = 0;
  23265. Scene.MinDeltaTime = 1.0;
  23266. Scene.MaxDeltaTime = 1000.0;
  23267. /** The distance in pixel that you have to move to prevent some events */
  23268. Scene.DragMovementThreshold = 10; // in pixels
  23269. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23270. Scene.LongPressDelay = 500; // in milliseconds
  23271. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23272. Scene.DoubleClickDelay = 300; // in milliseconds
  23273. /** If you need to check double click without raising a single click at first click, enable this flag */
  23274. Scene.ExclusiveDoubleClickMode = false;
  23275. return Scene;
  23276. }());
  23277. BABYLON.Scene = Scene;
  23278. })(BABYLON || (BABYLON = {}));
  23279. //# sourceMappingURL=babylon.scene.js.map
  23280. var BABYLON;
  23281. (function (BABYLON) {
  23282. var AssetContainer = /** @class */ (function () {
  23283. function AssetContainer(scene) {
  23284. // Objects
  23285. this.cameras = new Array();
  23286. this.lights = new Array();
  23287. this.meshes = new Array();
  23288. this.skeletons = new Array();
  23289. this.particleSystems = new Array();
  23290. this.animations = new Array();
  23291. this.multiMaterials = new Array();
  23292. this.materials = new Array();
  23293. this.morphTargetManagers = new Array();
  23294. this.geometries = new Array();
  23295. this.transformNodes = new Array();
  23296. this.lensFlareSystems = new Array();
  23297. this.shadowGenerators = new Array();
  23298. this.actionManagers = new Array();
  23299. this.sounds = new Array();
  23300. this.scene = scene;
  23301. }
  23302. AssetContainer.prototype.addAllToScene = function () {
  23303. var _this = this;
  23304. this.cameras.forEach(function (o) {
  23305. _this.scene.addCamera(o);
  23306. });
  23307. this.lights.forEach(function (o) {
  23308. _this.scene.addLight(o);
  23309. });
  23310. this.meshes.forEach(function (o) {
  23311. _this.scene.addMesh(o);
  23312. });
  23313. this.skeletons.forEach(function (o) {
  23314. _this.scene.addSkeleton(o);
  23315. });
  23316. this.particleSystems.forEach(function (o) {
  23317. _this.scene.addParticleSystem(o);
  23318. });
  23319. this.animations.forEach(function (o) {
  23320. _this.scene.addAnimation(o);
  23321. });
  23322. this.multiMaterials.forEach(function (o) {
  23323. _this.scene.addMultiMaterial(o);
  23324. });
  23325. this.materials.forEach(function (o) {
  23326. _this.scene.addMaterial(o);
  23327. });
  23328. this.morphTargetManagers.forEach(function (o) {
  23329. _this.scene.addMorphTargetManager(o);
  23330. });
  23331. this.geometries.forEach(function (o) {
  23332. _this.scene.addGeometry(o);
  23333. });
  23334. this.transformNodes.forEach(function (o) {
  23335. _this.scene.addTransformNode(o);
  23336. });
  23337. this.lensFlareSystems.forEach(function (o) {
  23338. _this.scene.addLensFlareSystem(o);
  23339. });
  23340. this.actionManagers.forEach(function (o) {
  23341. _this.scene.addActionManager(o);
  23342. });
  23343. this.sounds.forEach(function (o) {
  23344. o.play();
  23345. o.autoplay = true;
  23346. _this.scene.mainSoundTrack.AddSound(o);
  23347. });
  23348. };
  23349. AssetContainer.prototype.removeAllFromScene = function () {
  23350. var _this = this;
  23351. this.cameras.forEach(function (o) {
  23352. _this.scene.removeCamera(o);
  23353. });
  23354. this.lights.forEach(function (o) {
  23355. _this.scene.removeLight(o);
  23356. });
  23357. this.meshes.forEach(function (o) {
  23358. _this.scene.removeMesh(o);
  23359. });
  23360. this.skeletons.forEach(function (o) {
  23361. _this.scene.removeSkeleton(o);
  23362. });
  23363. this.particleSystems.forEach(function (o) {
  23364. _this.scene.removeParticleSystem(o);
  23365. });
  23366. this.animations.forEach(function (o) {
  23367. _this.scene.removeAnimation(o);
  23368. });
  23369. this.multiMaterials.forEach(function (o) {
  23370. _this.scene.removeMultiMaterial(o);
  23371. });
  23372. this.materials.forEach(function (o) {
  23373. _this.scene.removeMaterial(o);
  23374. });
  23375. this.morphTargetManagers.forEach(function (o) {
  23376. _this.scene.removeMorphTargetManager(o);
  23377. });
  23378. this.geometries.forEach(function (o) {
  23379. _this.scene.removeGeometry(o);
  23380. });
  23381. this.transformNodes.forEach(function (o) {
  23382. _this.scene.removeTransformNode(o);
  23383. });
  23384. this.lensFlareSystems.forEach(function (o) {
  23385. _this.scene.removeLensFlareSystem(o);
  23386. });
  23387. this.actionManagers.forEach(function (o) {
  23388. _this.scene.removeActionManager(o);
  23389. });
  23390. this.sounds.forEach(function (o) {
  23391. o.stop();
  23392. o.autoplay = false;
  23393. _this.scene.mainSoundTrack.RemoveSound(o);
  23394. });
  23395. };
  23396. return AssetContainer;
  23397. }());
  23398. BABYLON.AssetContainer = AssetContainer;
  23399. })(BABYLON || (BABYLON = {}));
  23400. //# sourceMappingURL=babylon.assetContainer.js.map
  23401. var BABYLON;
  23402. (function (BABYLON) {
  23403. var Buffer = /** @class */ (function () {
  23404. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23405. if (instanced === void 0) { instanced = false; }
  23406. if (engine instanceof BABYLON.Mesh) {
  23407. this._engine = engine.getScene().getEngine();
  23408. }
  23409. else {
  23410. this._engine = engine;
  23411. }
  23412. this._updatable = updatable;
  23413. this._data = data;
  23414. this._strideSize = stride;
  23415. if (!postponeInternalCreation) {
  23416. this.create();
  23417. }
  23418. this._instanced = instanced;
  23419. this._instanceDivisor = instanced ? 1 : 0;
  23420. }
  23421. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23422. // a lot of these parameters are ignored as they are overriden by the buffer
  23423. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23424. };
  23425. // Properties
  23426. Buffer.prototype.isUpdatable = function () {
  23427. return this._updatable;
  23428. };
  23429. Buffer.prototype.getData = function () {
  23430. return this._data;
  23431. };
  23432. Buffer.prototype.getBuffer = function () {
  23433. return this._buffer;
  23434. };
  23435. Buffer.prototype.getStrideSize = function () {
  23436. return this._strideSize;
  23437. };
  23438. Buffer.prototype.getIsInstanced = function () {
  23439. return this._instanced;
  23440. };
  23441. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23442. get: function () {
  23443. return this._instanceDivisor;
  23444. },
  23445. set: function (value) {
  23446. this._instanceDivisor = value;
  23447. if (value == 0) {
  23448. this._instanced = false;
  23449. }
  23450. else {
  23451. this._instanced = true;
  23452. }
  23453. },
  23454. enumerable: true,
  23455. configurable: true
  23456. });
  23457. // Methods
  23458. Buffer.prototype.create = function (data) {
  23459. if (data === void 0) { data = null; }
  23460. if (!data && this._buffer) {
  23461. return; // nothing to do
  23462. }
  23463. data = data || this._data;
  23464. if (!data) {
  23465. return;
  23466. }
  23467. if (!this._buffer) {
  23468. if (this._updatable) {
  23469. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23470. this._data = data;
  23471. }
  23472. else {
  23473. this._buffer = this._engine.createVertexBuffer(data);
  23474. }
  23475. }
  23476. else if (this._updatable) {
  23477. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23478. this._data = data;
  23479. }
  23480. };
  23481. Buffer.prototype._rebuild = function () {
  23482. this._buffer = null;
  23483. this.create(this._data);
  23484. };
  23485. Buffer.prototype.update = function (data) {
  23486. this.create(data);
  23487. };
  23488. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23489. if (!this._buffer) {
  23490. return;
  23491. }
  23492. if (this._updatable) {
  23493. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23494. this._data = null;
  23495. }
  23496. };
  23497. Buffer.prototype.dispose = function () {
  23498. if (!this._buffer) {
  23499. return;
  23500. }
  23501. if (this._engine._releaseBuffer(this._buffer)) {
  23502. this._buffer = null;
  23503. }
  23504. };
  23505. return Buffer;
  23506. }());
  23507. BABYLON.Buffer = Buffer;
  23508. })(BABYLON || (BABYLON = {}));
  23509. //# sourceMappingURL=babylon.buffer.js.map
  23510. var BABYLON;
  23511. (function (BABYLON) {
  23512. var VertexBuffer = /** @class */ (function () {
  23513. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23514. if (!stride) {
  23515. // Deduce stride from kind
  23516. switch (kind) {
  23517. case VertexBuffer.PositionKind:
  23518. stride = 3;
  23519. break;
  23520. case VertexBuffer.NormalKind:
  23521. stride = 3;
  23522. break;
  23523. case VertexBuffer.UVKind:
  23524. case VertexBuffer.UV2Kind:
  23525. case VertexBuffer.UV3Kind:
  23526. case VertexBuffer.UV4Kind:
  23527. case VertexBuffer.UV5Kind:
  23528. case VertexBuffer.UV6Kind:
  23529. stride = 2;
  23530. break;
  23531. case VertexBuffer.TangentKind:
  23532. case VertexBuffer.ColorKind:
  23533. stride = 4;
  23534. break;
  23535. case VertexBuffer.MatricesIndicesKind:
  23536. case VertexBuffer.MatricesIndicesExtraKind:
  23537. stride = 4;
  23538. break;
  23539. case VertexBuffer.MatricesWeightsKind:
  23540. case VertexBuffer.MatricesWeightsExtraKind:
  23541. default:
  23542. stride = 4;
  23543. break;
  23544. }
  23545. }
  23546. if (data instanceof BABYLON.Buffer) {
  23547. if (!stride) {
  23548. stride = data.getStrideSize();
  23549. }
  23550. this._buffer = data;
  23551. this._ownsBuffer = false;
  23552. }
  23553. else {
  23554. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23555. this._ownsBuffer = true;
  23556. }
  23557. this._stride = stride;
  23558. this._offset = offset ? offset : 0;
  23559. this._size = size ? size : stride;
  23560. this._kind = kind;
  23561. }
  23562. VertexBuffer.prototype._rebuild = function () {
  23563. if (!this._buffer) {
  23564. return;
  23565. }
  23566. this._buffer._rebuild();
  23567. };
  23568. /**
  23569. * Returns the kind of the VertexBuffer (string).
  23570. */
  23571. VertexBuffer.prototype.getKind = function () {
  23572. return this._kind;
  23573. };
  23574. // Properties
  23575. /**
  23576. * Boolean : is the VertexBuffer updatable ?
  23577. */
  23578. VertexBuffer.prototype.isUpdatable = function () {
  23579. return this._buffer.isUpdatable();
  23580. };
  23581. /**
  23582. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23583. */
  23584. VertexBuffer.prototype.getData = function () {
  23585. return this._buffer.getData();
  23586. };
  23587. /**
  23588. * Returns the WebGLBuffer associated to the VertexBuffer.
  23589. */
  23590. VertexBuffer.prototype.getBuffer = function () {
  23591. return this._buffer.getBuffer();
  23592. };
  23593. /**
  23594. * Returns the stride of the VertexBuffer (integer).
  23595. */
  23596. VertexBuffer.prototype.getStrideSize = function () {
  23597. return this._stride;
  23598. };
  23599. /**
  23600. * Returns the offset (integer).
  23601. */
  23602. VertexBuffer.prototype.getOffset = function () {
  23603. return this._offset;
  23604. };
  23605. /**
  23606. * Returns the VertexBuffer total size (integer).
  23607. */
  23608. VertexBuffer.prototype.getSize = function () {
  23609. return this._size;
  23610. };
  23611. /**
  23612. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23613. */
  23614. VertexBuffer.prototype.getIsInstanced = function () {
  23615. return this._buffer.getIsInstanced();
  23616. };
  23617. /**
  23618. * Returns the instancing divisor, zero for non-instanced (integer).
  23619. */
  23620. VertexBuffer.prototype.getInstanceDivisor = function () {
  23621. return this._buffer.instanceDivisor;
  23622. };
  23623. // Methods
  23624. /**
  23625. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23626. * Returns the created WebGLBuffer.
  23627. */
  23628. VertexBuffer.prototype.create = function (data) {
  23629. return this._buffer.create(data);
  23630. };
  23631. /**
  23632. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23633. * This function will create a new buffer if the current one is not updatable
  23634. * Returns the updated WebGLBuffer.
  23635. */
  23636. VertexBuffer.prototype.update = function (data) {
  23637. return this._buffer.update(data);
  23638. };
  23639. /**
  23640. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23641. * Returns the directly updated WebGLBuffer.
  23642. */
  23643. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23644. return this._buffer.updateDirectly(data, offset);
  23645. };
  23646. /**
  23647. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23648. */
  23649. VertexBuffer.prototype.dispose = function () {
  23650. if (this._ownsBuffer) {
  23651. this._buffer.dispose();
  23652. }
  23653. };
  23654. Object.defineProperty(VertexBuffer, "PositionKind", {
  23655. get: function () {
  23656. return VertexBuffer._PositionKind;
  23657. },
  23658. enumerable: true,
  23659. configurable: true
  23660. });
  23661. Object.defineProperty(VertexBuffer, "NormalKind", {
  23662. get: function () {
  23663. return VertexBuffer._NormalKind;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. Object.defineProperty(VertexBuffer, "TangentKind", {
  23669. get: function () {
  23670. return VertexBuffer._TangentKind;
  23671. },
  23672. enumerable: true,
  23673. configurable: true
  23674. });
  23675. Object.defineProperty(VertexBuffer, "UVKind", {
  23676. get: function () {
  23677. return VertexBuffer._UVKind;
  23678. },
  23679. enumerable: true,
  23680. configurable: true
  23681. });
  23682. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23683. get: function () {
  23684. return VertexBuffer._UV2Kind;
  23685. },
  23686. enumerable: true,
  23687. configurable: true
  23688. });
  23689. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23690. get: function () {
  23691. return VertexBuffer._UV3Kind;
  23692. },
  23693. enumerable: true,
  23694. configurable: true
  23695. });
  23696. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23697. get: function () {
  23698. return VertexBuffer._UV4Kind;
  23699. },
  23700. enumerable: true,
  23701. configurable: true
  23702. });
  23703. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23704. get: function () {
  23705. return VertexBuffer._UV5Kind;
  23706. },
  23707. enumerable: true,
  23708. configurable: true
  23709. });
  23710. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23711. get: function () {
  23712. return VertexBuffer._UV6Kind;
  23713. },
  23714. enumerable: true,
  23715. configurable: true
  23716. });
  23717. Object.defineProperty(VertexBuffer, "ColorKind", {
  23718. get: function () {
  23719. return VertexBuffer._ColorKind;
  23720. },
  23721. enumerable: true,
  23722. configurable: true
  23723. });
  23724. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23725. get: function () {
  23726. return VertexBuffer._MatricesIndicesKind;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23732. get: function () {
  23733. return VertexBuffer._MatricesWeightsKind;
  23734. },
  23735. enumerable: true,
  23736. configurable: true
  23737. });
  23738. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23739. get: function () {
  23740. return VertexBuffer._MatricesIndicesExtraKind;
  23741. },
  23742. enumerable: true,
  23743. configurable: true
  23744. });
  23745. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23746. get: function () {
  23747. return VertexBuffer._MatricesWeightsExtraKind;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. // Enums
  23753. VertexBuffer._PositionKind = "position";
  23754. VertexBuffer._NormalKind = "normal";
  23755. VertexBuffer._TangentKind = "tangent";
  23756. VertexBuffer._UVKind = "uv";
  23757. VertexBuffer._UV2Kind = "uv2";
  23758. VertexBuffer._UV3Kind = "uv3";
  23759. VertexBuffer._UV4Kind = "uv4";
  23760. VertexBuffer._UV5Kind = "uv5";
  23761. VertexBuffer._UV6Kind = "uv6";
  23762. VertexBuffer._ColorKind = "color";
  23763. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23764. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23765. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23766. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23767. return VertexBuffer;
  23768. }());
  23769. BABYLON.VertexBuffer = VertexBuffer;
  23770. })(BABYLON || (BABYLON = {}));
  23771. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23772. var BABYLON;
  23773. (function (BABYLON) {
  23774. /**
  23775. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  23776. */
  23777. var DummyInternalTextureTracker = /** @class */ (function () {
  23778. function DummyInternalTextureTracker() {
  23779. /**
  23780. * Gets or set the previous tracker in the list
  23781. */
  23782. this.previous = null;
  23783. /**
  23784. * Gets or set the next tracker in the list
  23785. */
  23786. this.next = null;
  23787. }
  23788. return DummyInternalTextureTracker;
  23789. }());
  23790. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  23791. })(BABYLON || (BABYLON = {}));
  23792. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  23793. var BABYLON;
  23794. (function (BABYLON) {
  23795. /**
  23796. * Class used to store data associated with WebGL texture data for the engine
  23797. * This class should not be used directly
  23798. */
  23799. var InternalTexture = /** @class */ (function () {
  23800. /**
  23801. * Creates a new InternalTexture
  23802. * @param engine defines the engine to use
  23803. * @param dataSource defines the type of data that will be used
  23804. */
  23805. function InternalTexture(engine, dataSource) {
  23806. /**
  23807. * Observable called when the texture is loaded
  23808. */
  23809. this.onLoadedObservable = new BABYLON.Observable();
  23810. /**
  23811. * Gets or set the previous tracker in the list
  23812. */
  23813. this.previous = null;
  23814. /**
  23815. * Gets or set the next tracker in the list
  23816. */
  23817. this.next = null;
  23818. // Private
  23819. /** @ignore */
  23820. this._initialSlot = -1;
  23821. /** @ignore */
  23822. this._designatedSlot = -1;
  23823. /** @ignore */
  23824. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23825. /** @ignore */
  23826. this._references = 1;
  23827. this._engine = engine;
  23828. this._dataSource = dataSource;
  23829. this._webGLTexture = engine._createTexture();
  23830. }
  23831. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23832. /**
  23833. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  23834. */
  23835. get: function () {
  23836. return this._dataSource;
  23837. },
  23838. enumerable: true,
  23839. configurable: true
  23840. });
  23841. /**
  23842. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  23843. */
  23844. InternalTexture.prototype.incrementReferences = function () {
  23845. this._references++;
  23846. };
  23847. /**
  23848. * Change the size of the texture (not the size of the content)
  23849. * @param width defines the new width
  23850. * @param height defines the new height
  23851. * @param depth defines the new depth (1 by default)
  23852. */
  23853. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23854. if (depth === void 0) { depth = 1; }
  23855. this.width = width;
  23856. this.height = height;
  23857. this.depth = depth;
  23858. this.baseWidth = width;
  23859. this.baseHeight = height;
  23860. this.baseDepth = depth;
  23861. this._size = width * height * depth;
  23862. };
  23863. /** @ignore */
  23864. InternalTexture.prototype._rebuild = function () {
  23865. var _this = this;
  23866. var proxy;
  23867. this.isReady = false;
  23868. this._cachedCoordinatesMode = null;
  23869. this._cachedWrapU = null;
  23870. this._cachedWrapV = null;
  23871. this._cachedAnisotropicFilteringLevel = null;
  23872. switch (this._dataSource) {
  23873. case InternalTexture.DATASOURCE_TEMP:
  23874. return;
  23875. case InternalTexture.DATASOURCE_URL:
  23876. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23877. _this.isReady = true;
  23878. }, null, this._buffer, undefined, this.format);
  23879. proxy._swapAndDie(this);
  23880. return;
  23881. case InternalTexture.DATASOURCE_RAW:
  23882. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23883. proxy._swapAndDie(this);
  23884. this.isReady = true;
  23885. return;
  23886. case InternalTexture.DATASOURCE_RAW3D:
  23887. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23888. proxy._swapAndDie(this);
  23889. this.isReady = true;
  23890. return;
  23891. case InternalTexture.DATASOURCE_DYNAMIC:
  23892. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23893. proxy._swapAndDie(this);
  23894. // The engine will make sure to update content so no need to flag it as isReady = true
  23895. return;
  23896. case InternalTexture.DATASOURCE_RENDERTARGET:
  23897. var options = new BABYLON.RenderTargetCreationOptions();
  23898. options.generateDepthBuffer = this._generateDepthBuffer;
  23899. options.generateMipMaps = this.generateMipMaps;
  23900. options.generateStencilBuffer = this._generateStencilBuffer;
  23901. options.samplingMode = this.samplingMode;
  23902. options.type = this.type;
  23903. if (this.isCube) {
  23904. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23905. }
  23906. else {
  23907. var size = {
  23908. width: this.width,
  23909. height: this.height
  23910. };
  23911. proxy = this._engine.createRenderTargetTexture(size, options);
  23912. }
  23913. proxy._swapAndDie(this);
  23914. this.isReady = true;
  23915. return;
  23916. case InternalTexture.DATASOURCE_CUBE:
  23917. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23918. _this.isReady = true;
  23919. }, null, this.format, this._extension);
  23920. proxy._swapAndDie(this);
  23921. return;
  23922. case InternalTexture.DATASOURCE_CUBERAW:
  23923. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23924. proxy._swapAndDie(this);
  23925. this.isReady = true;
  23926. return;
  23927. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23928. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23929. if (proxy) {
  23930. proxy._swapAndDie(_this);
  23931. }
  23932. _this.isReady = true;
  23933. }, null, this.format, this._extension);
  23934. return;
  23935. }
  23936. };
  23937. InternalTexture.prototype._swapAndDie = function (target) {
  23938. target._webGLTexture = this._webGLTexture;
  23939. if (this._framebuffer) {
  23940. target._framebuffer = this._framebuffer;
  23941. }
  23942. if (this._depthStencilBuffer) {
  23943. target._depthStencilBuffer = this._depthStencilBuffer;
  23944. }
  23945. if (this._lodTextureHigh) {
  23946. if (target._lodTextureHigh) {
  23947. target._lodTextureHigh.dispose();
  23948. }
  23949. target._lodTextureHigh = this._lodTextureHigh;
  23950. }
  23951. if (this._lodTextureMid) {
  23952. if (target._lodTextureMid) {
  23953. target._lodTextureMid.dispose();
  23954. }
  23955. target._lodTextureMid = this._lodTextureMid;
  23956. }
  23957. if (this._lodTextureLow) {
  23958. if (target._lodTextureLow) {
  23959. target._lodTextureLow.dispose();
  23960. }
  23961. target._lodTextureLow = this._lodTextureLow;
  23962. }
  23963. var cache = this._engine.getLoadedTexturesCache();
  23964. var index = cache.indexOf(this);
  23965. if (index !== -1) {
  23966. cache.splice(index, 1);
  23967. }
  23968. };
  23969. /**
  23970. * Dispose the current allocated resources
  23971. */
  23972. InternalTexture.prototype.dispose = function () {
  23973. if (!this._webGLTexture) {
  23974. return;
  23975. }
  23976. this._references--;
  23977. if (this._references === 0) {
  23978. this._engine._releaseTexture(this);
  23979. this._webGLTexture = null;
  23980. this.previous = null;
  23981. this.next = null;
  23982. }
  23983. };
  23984. /**
  23985. * The source of the texture data is unknown
  23986. */
  23987. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23988. /**
  23989. * Texture data comes from an URL
  23990. */
  23991. InternalTexture.DATASOURCE_URL = 1;
  23992. /**
  23993. * Texture data is only used for temporary storage
  23994. */
  23995. InternalTexture.DATASOURCE_TEMP = 2;
  23996. /**
  23997. * Texture data comes from raw data (ArrayBuffer)
  23998. */
  23999. InternalTexture.DATASOURCE_RAW = 3;
  24000. /**
  24001. * Texture content is dynamic (video or dynamic texture)
  24002. */
  24003. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24004. /**
  24005. * Texture content is generated by rendering to it
  24006. */
  24007. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24008. /**
  24009. * Texture content is part of a multi render target process
  24010. */
  24011. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24012. /**
  24013. * Texture data comes from a cube data file
  24014. */
  24015. InternalTexture.DATASOURCE_CUBE = 7;
  24016. /**
  24017. * Texture data comes from a raw cube data
  24018. */
  24019. InternalTexture.DATASOURCE_CUBERAW = 8;
  24020. /**
  24021. * Texture data come from a prefiltered cube data file
  24022. */
  24023. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24024. /**
  24025. * Texture content is raw 3D data
  24026. */
  24027. InternalTexture.DATASOURCE_RAW3D = 10;
  24028. return InternalTexture;
  24029. }());
  24030. BABYLON.InternalTexture = InternalTexture;
  24031. })(BABYLON || (BABYLON = {}));
  24032. //# sourceMappingURL=babylon.internalTexture.js.map
  24033. var BABYLON;
  24034. (function (BABYLON) {
  24035. var BaseTexture = /** @class */ (function () {
  24036. function BaseTexture(scene) {
  24037. this._hasAlpha = false;
  24038. this.getAlphaFromRGB = false;
  24039. this.level = 1;
  24040. this.coordinatesIndex = 0;
  24041. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24042. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24043. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24044. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24045. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24046. this.isCube = false;
  24047. this.is3D = false;
  24048. this.gammaSpace = true;
  24049. this.invertZ = false;
  24050. this.lodLevelInAlpha = false;
  24051. this.lodGenerationOffset = 0.0;
  24052. this.lodGenerationScale = 0.8;
  24053. this.isRenderTarget = false;
  24054. this.animations = new Array();
  24055. /**
  24056. * An event triggered when the texture is disposed.
  24057. * @type {BABYLON.Observable}
  24058. */
  24059. this.onDisposeObservable = new BABYLON.Observable();
  24060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24061. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24062. if (this._scene) {
  24063. this._scene.textures.push(this);
  24064. }
  24065. this._uid = null;
  24066. }
  24067. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24068. get: function () {
  24069. return this._hasAlpha;
  24070. },
  24071. set: function (value) {
  24072. if (this._hasAlpha === value) {
  24073. return;
  24074. }
  24075. this._hasAlpha = value;
  24076. if (this._scene) {
  24077. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24078. }
  24079. },
  24080. enumerable: true,
  24081. configurable: true
  24082. });
  24083. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24084. get: function () {
  24085. return this._coordinatesMode;
  24086. },
  24087. set: function (value) {
  24088. if (this._coordinatesMode === value) {
  24089. return;
  24090. }
  24091. this._coordinatesMode = value;
  24092. if (this._scene) {
  24093. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24094. }
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(BaseTexture.prototype, "uid", {
  24100. get: function () {
  24101. if (!this._uid) {
  24102. this._uid = BABYLON.Tools.RandomId();
  24103. }
  24104. return this._uid;
  24105. },
  24106. enumerable: true,
  24107. configurable: true
  24108. });
  24109. BaseTexture.prototype.toString = function () {
  24110. return this.name;
  24111. };
  24112. BaseTexture.prototype.getClassName = function () {
  24113. return "BaseTexture";
  24114. };
  24115. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24116. set: function (callback) {
  24117. if (this._onDisposeObserver) {
  24118. this.onDisposeObservable.remove(this._onDisposeObserver);
  24119. }
  24120. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24121. },
  24122. enumerable: true,
  24123. configurable: true
  24124. });
  24125. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24126. get: function () {
  24127. return true;
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. BaseTexture.prototype.getScene = function () {
  24133. return this._scene;
  24134. };
  24135. BaseTexture.prototype.getTextureMatrix = function () {
  24136. return BABYLON.Matrix.IdentityReadOnly;
  24137. };
  24138. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24139. return BABYLON.Matrix.IdentityReadOnly;
  24140. };
  24141. BaseTexture.prototype.getInternalTexture = function () {
  24142. return this._texture;
  24143. };
  24144. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24145. return !this.isBlocking || this.isReady();
  24146. };
  24147. BaseTexture.prototype.isReady = function () {
  24148. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24149. this.delayLoad();
  24150. return false;
  24151. }
  24152. if (this._texture) {
  24153. return this._texture.isReady;
  24154. }
  24155. return false;
  24156. };
  24157. BaseTexture.prototype.getSize = function () {
  24158. if (this._texture && this._texture.width) {
  24159. return new BABYLON.Size(this._texture.width, this._texture.height);
  24160. }
  24161. if (this._texture && this._texture._size) {
  24162. return new BABYLON.Size(this._texture._size, this._texture._size);
  24163. }
  24164. return BABYLON.Size.Zero();
  24165. };
  24166. BaseTexture.prototype.getBaseSize = function () {
  24167. if (!this.isReady() || !this._texture)
  24168. return BABYLON.Size.Zero();
  24169. if (this._texture._size) {
  24170. return new BABYLON.Size(this._texture._size, this._texture._size);
  24171. }
  24172. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24173. };
  24174. BaseTexture.prototype.scale = function (ratio) {
  24175. };
  24176. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24177. get: function () {
  24178. return false;
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24184. if (!this._scene) {
  24185. return null;
  24186. }
  24187. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24188. for (var index = 0; index < texturesCache.length; index++) {
  24189. var texturesCacheEntry = texturesCache[index];
  24190. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24191. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24192. texturesCacheEntry.incrementReferences();
  24193. return texturesCacheEntry;
  24194. }
  24195. }
  24196. }
  24197. return null;
  24198. };
  24199. BaseTexture.prototype._rebuild = function () {
  24200. };
  24201. BaseTexture.prototype.delayLoad = function () {
  24202. };
  24203. BaseTexture.prototype.clone = function () {
  24204. return null;
  24205. };
  24206. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24207. get: function () {
  24208. if (!this._texture) {
  24209. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24210. }
  24211. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24212. },
  24213. enumerable: true,
  24214. configurable: true
  24215. });
  24216. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24217. get: function () {
  24218. if (!this._texture) {
  24219. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24220. }
  24221. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24222. },
  24223. enumerable: true,
  24224. configurable: true
  24225. });
  24226. BaseTexture.prototype.readPixels = function (faceIndex) {
  24227. if (faceIndex === void 0) { faceIndex = 0; }
  24228. if (!this._texture) {
  24229. return null;
  24230. }
  24231. var size = this.getSize();
  24232. var scene = this.getScene();
  24233. if (!scene) {
  24234. return null;
  24235. }
  24236. var engine = scene.getEngine();
  24237. if (this._texture.isCube) {
  24238. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24239. }
  24240. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24241. };
  24242. BaseTexture.prototype.releaseInternalTexture = function () {
  24243. if (this._texture) {
  24244. this._texture.dispose();
  24245. this._texture = null;
  24246. }
  24247. };
  24248. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24249. get: function () {
  24250. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24251. return null;
  24252. }
  24253. if (!this._texture._sphericalPolynomial) {
  24254. this._texture._sphericalPolynomial =
  24255. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24256. }
  24257. return this._texture._sphericalPolynomial;
  24258. },
  24259. set: function (value) {
  24260. if (this._texture) {
  24261. this._texture._sphericalPolynomial = value;
  24262. }
  24263. },
  24264. enumerable: true,
  24265. configurable: true
  24266. });
  24267. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24268. get: function () {
  24269. if (this._texture) {
  24270. return this._texture._lodTextureHigh;
  24271. }
  24272. return null;
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24278. get: function () {
  24279. if (this._texture) {
  24280. return this._texture._lodTextureMid;
  24281. }
  24282. return null;
  24283. },
  24284. enumerable: true,
  24285. configurable: true
  24286. });
  24287. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24288. get: function () {
  24289. if (this._texture) {
  24290. return this._texture._lodTextureLow;
  24291. }
  24292. return null;
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. BaseTexture.prototype.dispose = function () {
  24298. if (!this._scene) {
  24299. return;
  24300. }
  24301. // Animations
  24302. this._scene.stopAnimation(this);
  24303. // Remove from scene
  24304. this._scene._removePendingData(this);
  24305. var index = this._scene.textures.indexOf(this);
  24306. if (index >= 0) {
  24307. this._scene.textures.splice(index, 1);
  24308. }
  24309. if (this._texture === undefined) {
  24310. return;
  24311. }
  24312. // Release
  24313. this.releaseInternalTexture();
  24314. // Callback
  24315. this.onDisposeObservable.notifyObservers(this);
  24316. this.onDisposeObservable.clear();
  24317. };
  24318. BaseTexture.prototype.serialize = function () {
  24319. if (!this.name) {
  24320. return null;
  24321. }
  24322. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24323. // Animations
  24324. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24325. return serializationObject;
  24326. };
  24327. BaseTexture.WhenAllReady = function (textures, callback) {
  24328. var numRemaining = textures.length;
  24329. if (numRemaining === 0) {
  24330. callback();
  24331. return;
  24332. }
  24333. var _loop_1 = function () {
  24334. texture = textures[i];
  24335. if (texture.isReady()) {
  24336. if (--numRemaining === 0) {
  24337. callback();
  24338. }
  24339. }
  24340. else {
  24341. onLoadObservable = texture.onLoadObservable;
  24342. var onLoadCallback_1 = function () {
  24343. onLoadObservable.removeCallback(onLoadCallback_1);
  24344. if (--numRemaining === 0) {
  24345. callback();
  24346. }
  24347. };
  24348. onLoadObservable.add(onLoadCallback_1);
  24349. }
  24350. };
  24351. var texture, onLoadObservable;
  24352. for (var i = 0; i < textures.length; i++) {
  24353. _loop_1();
  24354. }
  24355. };
  24356. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24357. __decorate([
  24358. BABYLON.serialize()
  24359. ], BaseTexture.prototype, "name", void 0);
  24360. __decorate([
  24361. BABYLON.serialize("hasAlpha")
  24362. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24363. __decorate([
  24364. BABYLON.serialize()
  24365. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24366. __decorate([
  24367. BABYLON.serialize()
  24368. ], BaseTexture.prototype, "level", void 0);
  24369. __decorate([
  24370. BABYLON.serialize()
  24371. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24372. __decorate([
  24373. BABYLON.serialize("coordinatesMode")
  24374. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24375. __decorate([
  24376. BABYLON.serialize()
  24377. ], BaseTexture.prototype, "wrapU", void 0);
  24378. __decorate([
  24379. BABYLON.serialize()
  24380. ], BaseTexture.prototype, "wrapV", void 0);
  24381. __decorate([
  24382. BABYLON.serialize()
  24383. ], BaseTexture.prototype, "wrapR", void 0);
  24384. __decorate([
  24385. BABYLON.serialize()
  24386. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24387. __decorate([
  24388. BABYLON.serialize()
  24389. ], BaseTexture.prototype, "isCube", void 0);
  24390. __decorate([
  24391. BABYLON.serialize()
  24392. ], BaseTexture.prototype, "is3D", void 0);
  24393. __decorate([
  24394. BABYLON.serialize()
  24395. ], BaseTexture.prototype, "gammaSpace", void 0);
  24396. __decorate([
  24397. BABYLON.serialize()
  24398. ], BaseTexture.prototype, "invertZ", void 0);
  24399. __decorate([
  24400. BABYLON.serialize()
  24401. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24402. __decorate([
  24403. BABYLON.serialize()
  24404. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24405. __decorate([
  24406. BABYLON.serialize()
  24407. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24408. __decorate([
  24409. BABYLON.serialize()
  24410. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24411. return BaseTexture;
  24412. }());
  24413. BABYLON.BaseTexture = BaseTexture;
  24414. })(BABYLON || (BABYLON = {}));
  24415. //# sourceMappingURL=babylon.baseTexture.js.map
  24416. var BABYLON;
  24417. (function (BABYLON) {
  24418. var Texture = /** @class */ (function (_super) {
  24419. __extends(Texture, _super);
  24420. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24421. if (noMipmap === void 0) { noMipmap = false; }
  24422. if (invertY === void 0) { invertY = true; }
  24423. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24424. if (onLoad === void 0) { onLoad = null; }
  24425. if (onError === void 0) { onError = null; }
  24426. if (buffer === void 0) { buffer = null; }
  24427. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24428. var _this = _super.call(this, scene) || this;
  24429. _this.uOffset = 0;
  24430. _this.vOffset = 0;
  24431. _this.uScale = 1.0;
  24432. _this.vScale = 1.0;
  24433. _this.uAng = 0;
  24434. _this.vAng = 0;
  24435. _this.wAng = 0;
  24436. _this._isBlocking = true;
  24437. _this.name = url || "";
  24438. _this.url = url;
  24439. _this._noMipmap = noMipmap;
  24440. _this._invertY = invertY;
  24441. _this._samplingMode = samplingMode;
  24442. _this._buffer = buffer;
  24443. _this._deleteBuffer = deleteBuffer;
  24444. if (format) {
  24445. _this._format = format;
  24446. }
  24447. scene = _this.getScene();
  24448. if (!scene) {
  24449. return _this;
  24450. }
  24451. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24452. var load = function () {
  24453. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24454. _this.onLoadObservable.notifyObservers(_this);
  24455. }
  24456. if (onLoad) {
  24457. onLoad();
  24458. }
  24459. if (!_this.isBlocking && scene) {
  24460. scene.resetCachedMaterial();
  24461. }
  24462. };
  24463. if (!_this.url) {
  24464. _this._delayedOnLoad = load;
  24465. _this._delayedOnError = onError;
  24466. return _this;
  24467. }
  24468. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24469. if (!_this._texture) {
  24470. if (!scene.useDelayedTextureLoading) {
  24471. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24472. if (deleteBuffer) {
  24473. delete _this._buffer;
  24474. }
  24475. }
  24476. else {
  24477. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24478. _this._delayedOnLoad = load;
  24479. _this._delayedOnError = onError;
  24480. }
  24481. }
  24482. else {
  24483. if (_this._texture.isReady) {
  24484. BABYLON.Tools.SetImmediate(function () { return load(); });
  24485. }
  24486. else {
  24487. _this._texture.onLoadedObservable.add(load);
  24488. }
  24489. }
  24490. return _this;
  24491. }
  24492. Object.defineProperty(Texture.prototype, "noMipmap", {
  24493. get: function () {
  24494. return this._noMipmap;
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Texture.prototype, "isBlocking", {
  24500. get: function () {
  24501. return this._isBlocking;
  24502. },
  24503. set: function (value) {
  24504. this._isBlocking = value;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. Object.defineProperty(Texture.prototype, "samplingMode", {
  24510. get: function () {
  24511. return this._samplingMode;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Texture.prototype.updateURL = function (url) {
  24517. this.url = url;
  24518. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24519. this.delayLoad();
  24520. };
  24521. Texture.prototype.delayLoad = function () {
  24522. var _this = this;
  24523. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24524. return;
  24525. }
  24526. var scene = this.getScene();
  24527. if (!scene) {
  24528. return;
  24529. }
  24530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24531. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24532. if (!this._texture) {
  24533. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24534. if (this._deleteBuffer) {
  24535. delete this._buffer;
  24536. }
  24537. }
  24538. else {
  24539. if (this._texture.isReady) {
  24540. BABYLON.Tools.SetImmediate(function () {
  24541. if (!_this._delayedOnLoad) {
  24542. return;
  24543. }
  24544. _this._delayedOnLoad();
  24545. });
  24546. }
  24547. else {
  24548. if (this._delayedOnLoad) {
  24549. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24550. }
  24551. }
  24552. }
  24553. };
  24554. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24555. if (!this._texture) {
  24556. return;
  24557. }
  24558. var scene = this.getScene();
  24559. if (!scene) {
  24560. return;
  24561. }
  24562. this._samplingMode = samplingMode;
  24563. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24564. };
  24565. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24566. x *= this.uScale;
  24567. y *= this.vScale;
  24568. x -= 0.5 * this.uScale;
  24569. y -= 0.5 * this.vScale;
  24570. z -= 0.5;
  24571. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24572. t.x += 0.5 * this.uScale + this.uOffset;
  24573. t.y += 0.5 * this.vScale + this.vOffset;
  24574. t.z += 0.5;
  24575. };
  24576. Texture.prototype.getTextureMatrix = function () {
  24577. var _this = this;
  24578. if (this.uOffset === this._cachedUOffset &&
  24579. this.vOffset === this._cachedVOffset &&
  24580. this.uScale === this._cachedUScale &&
  24581. this.vScale === this._cachedVScale &&
  24582. this.uAng === this._cachedUAng &&
  24583. this.vAng === this._cachedVAng &&
  24584. this.wAng === this._cachedWAng) {
  24585. return this._cachedTextureMatrix;
  24586. }
  24587. this._cachedUOffset = this.uOffset;
  24588. this._cachedVOffset = this.vOffset;
  24589. this._cachedUScale = this.uScale;
  24590. this._cachedVScale = this.vScale;
  24591. this._cachedUAng = this.uAng;
  24592. this._cachedVAng = this.vAng;
  24593. this._cachedWAng = this.wAng;
  24594. if (!this._cachedTextureMatrix) {
  24595. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24596. this._rowGenerationMatrix = new BABYLON.Matrix();
  24597. this._t0 = BABYLON.Vector3.Zero();
  24598. this._t1 = BABYLON.Vector3.Zero();
  24599. this._t2 = BABYLON.Vector3.Zero();
  24600. }
  24601. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24602. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24603. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24604. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24605. this._t1.subtractInPlace(this._t0);
  24606. this._t2.subtractInPlace(this._t0);
  24607. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24608. this._cachedTextureMatrix.m[0] = this._t1.x;
  24609. this._cachedTextureMatrix.m[1] = this._t1.y;
  24610. this._cachedTextureMatrix.m[2] = this._t1.z;
  24611. this._cachedTextureMatrix.m[4] = this._t2.x;
  24612. this._cachedTextureMatrix.m[5] = this._t2.y;
  24613. this._cachedTextureMatrix.m[6] = this._t2.z;
  24614. this._cachedTextureMatrix.m[8] = this._t0.x;
  24615. this._cachedTextureMatrix.m[9] = this._t0.y;
  24616. this._cachedTextureMatrix.m[10] = this._t0.z;
  24617. var scene = this.getScene();
  24618. if (!scene) {
  24619. return this._cachedTextureMatrix;
  24620. }
  24621. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24622. return mat.hasTexture(_this);
  24623. });
  24624. return this._cachedTextureMatrix;
  24625. };
  24626. Texture.prototype.getReflectionTextureMatrix = function () {
  24627. var _this = this;
  24628. var scene = this.getScene();
  24629. if (!scene) {
  24630. return this._cachedTextureMatrix;
  24631. }
  24632. if (this.uOffset === this._cachedUOffset &&
  24633. this.vOffset === this._cachedVOffset &&
  24634. this.uScale === this._cachedUScale &&
  24635. this.vScale === this._cachedVScale &&
  24636. this.coordinatesMode === this._cachedCoordinatesMode) {
  24637. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24638. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24639. return this._cachedTextureMatrix;
  24640. }
  24641. }
  24642. else {
  24643. return this._cachedTextureMatrix;
  24644. }
  24645. }
  24646. if (!this._cachedTextureMatrix) {
  24647. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24648. }
  24649. if (!this._projectionModeMatrix) {
  24650. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24651. }
  24652. this._cachedUOffset = this.uOffset;
  24653. this._cachedVOffset = this.vOffset;
  24654. this._cachedUScale = this.uScale;
  24655. this._cachedVScale = this.vScale;
  24656. this._cachedCoordinatesMode = this.coordinatesMode;
  24657. switch (this.coordinatesMode) {
  24658. case Texture.PLANAR_MODE:
  24659. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24660. this._cachedTextureMatrix[0] = this.uScale;
  24661. this._cachedTextureMatrix[5] = this.vScale;
  24662. this._cachedTextureMatrix[12] = this.uOffset;
  24663. this._cachedTextureMatrix[13] = this.vOffset;
  24664. break;
  24665. case Texture.PROJECTION_MODE:
  24666. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24667. this._projectionModeMatrix.m[0] = 0.5;
  24668. this._projectionModeMatrix.m[5] = -0.5;
  24669. this._projectionModeMatrix.m[10] = 0.0;
  24670. this._projectionModeMatrix.m[12] = 0.5;
  24671. this._projectionModeMatrix.m[13] = 0.5;
  24672. this._projectionModeMatrix.m[14] = 1.0;
  24673. this._projectionModeMatrix.m[15] = 1.0;
  24674. var projectionMatrix = scene.getProjectionMatrix();
  24675. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24676. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24677. break;
  24678. default:
  24679. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24680. break;
  24681. }
  24682. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24683. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24684. });
  24685. return this._cachedTextureMatrix;
  24686. };
  24687. Texture.prototype.clone = function () {
  24688. var _this = this;
  24689. return BABYLON.SerializationHelper.Clone(function () {
  24690. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24691. }, this);
  24692. };
  24693. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24694. get: function () {
  24695. if (!this._onLoadObservable) {
  24696. this._onLoadObservable = new BABYLON.Observable();
  24697. }
  24698. return this._onLoadObservable;
  24699. },
  24700. enumerable: true,
  24701. configurable: true
  24702. });
  24703. Texture.prototype.serialize = function () {
  24704. var serializationObject = _super.prototype.serialize.call(this);
  24705. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24706. serializationObject.base64String = this._buffer;
  24707. serializationObject.name = serializationObject.name.replace("data:", "");
  24708. }
  24709. return serializationObject;
  24710. };
  24711. Texture.prototype.getClassName = function () {
  24712. return "Texture";
  24713. };
  24714. Texture.prototype.dispose = function () {
  24715. _super.prototype.dispose.call(this);
  24716. if (this.onLoadObservable) {
  24717. this.onLoadObservable.clear();
  24718. this._onLoadObservable = null;
  24719. }
  24720. this._delayedOnLoad = null;
  24721. this._delayedOnError = null;
  24722. };
  24723. // Statics
  24724. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24725. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24726. if (onLoad === void 0) { onLoad = null; }
  24727. if (onError === void 0) { onError = null; }
  24728. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24729. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24730. };
  24731. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24732. if (parsedTexture.customType) {
  24733. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24734. // Update Sampling Mode
  24735. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24736. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24737. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24738. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24739. }
  24740. }
  24741. return parsedCustomTexture;
  24742. }
  24743. if (parsedTexture.isCube) {
  24744. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24745. }
  24746. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24747. return null;
  24748. }
  24749. var texture = BABYLON.SerializationHelper.Parse(function () {
  24750. var generateMipMaps = true;
  24751. if (parsedTexture.noMipmap) {
  24752. generateMipMaps = false;
  24753. }
  24754. if (parsedTexture.mirrorPlane) {
  24755. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24756. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24757. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24758. return mirrorTexture;
  24759. }
  24760. else if (parsedTexture.isRenderTarget) {
  24761. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24762. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24763. return renderTargetTexture;
  24764. }
  24765. else {
  24766. var texture;
  24767. if (parsedTexture.base64String) {
  24768. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24769. }
  24770. else {
  24771. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24772. }
  24773. return texture;
  24774. }
  24775. }, parsedTexture, scene);
  24776. // Update Sampling Mode
  24777. if (parsedTexture.samplingMode) {
  24778. var sampling = parsedTexture.samplingMode;
  24779. if (texture._samplingMode !== sampling) {
  24780. texture.updateSamplingMode(sampling);
  24781. }
  24782. }
  24783. // Animations
  24784. if (parsedTexture.animations) {
  24785. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24786. var parsedAnimation = parsedTexture.animations[animationIndex];
  24787. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24788. }
  24789. }
  24790. return texture;
  24791. };
  24792. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24793. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24794. if (noMipmap === void 0) { noMipmap = false; }
  24795. if (invertY === void 0) { invertY = true; }
  24796. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24797. if (onLoad === void 0) { onLoad = null; }
  24798. if (onError === void 0) { onError = null; }
  24799. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24800. if (name.substr(0, 5) !== "data:") {
  24801. name = "data:" + name;
  24802. }
  24803. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24804. };
  24805. // Constants
  24806. Texture.NEAREST_SAMPLINGMODE = 1;
  24807. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24808. Texture.BILINEAR_SAMPLINGMODE = 2;
  24809. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24810. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24811. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24812. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24813. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24814. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24815. Texture.NEAREST_LINEAR = 7;
  24816. Texture.NEAREST_NEAREST = 8;
  24817. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24818. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24819. Texture.LINEAR_LINEAR = 11;
  24820. Texture.LINEAR_NEAREST = 12;
  24821. Texture.EXPLICIT_MODE = 0;
  24822. Texture.SPHERICAL_MODE = 1;
  24823. Texture.PLANAR_MODE = 2;
  24824. Texture.CUBIC_MODE = 3;
  24825. Texture.PROJECTION_MODE = 4;
  24826. Texture.SKYBOX_MODE = 5;
  24827. Texture.INVCUBIC_MODE = 6;
  24828. Texture.EQUIRECTANGULAR_MODE = 7;
  24829. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24830. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24831. Texture.CLAMP_ADDRESSMODE = 0;
  24832. Texture.WRAP_ADDRESSMODE = 1;
  24833. Texture.MIRROR_ADDRESSMODE = 2;
  24834. __decorate([
  24835. BABYLON.serialize()
  24836. ], Texture.prototype, "url", void 0);
  24837. __decorate([
  24838. BABYLON.serialize()
  24839. ], Texture.prototype, "uOffset", void 0);
  24840. __decorate([
  24841. BABYLON.serialize()
  24842. ], Texture.prototype, "vOffset", void 0);
  24843. __decorate([
  24844. BABYLON.serialize()
  24845. ], Texture.prototype, "uScale", void 0);
  24846. __decorate([
  24847. BABYLON.serialize()
  24848. ], Texture.prototype, "vScale", void 0);
  24849. __decorate([
  24850. BABYLON.serialize()
  24851. ], Texture.prototype, "uAng", void 0);
  24852. __decorate([
  24853. BABYLON.serialize()
  24854. ], Texture.prototype, "vAng", void 0);
  24855. __decorate([
  24856. BABYLON.serialize()
  24857. ], Texture.prototype, "wAng", void 0);
  24858. __decorate([
  24859. BABYLON.serialize()
  24860. ], Texture.prototype, "isBlocking", null);
  24861. return Texture;
  24862. }(BABYLON.BaseTexture));
  24863. BABYLON.Texture = Texture;
  24864. })(BABYLON || (BABYLON = {}));
  24865. //# sourceMappingURL=babylon.texture.js.map
  24866. var BABYLON;
  24867. (function (BABYLON) {
  24868. var _InstancesBatch = /** @class */ (function () {
  24869. function _InstancesBatch() {
  24870. this.mustReturn = false;
  24871. this.visibleInstances = new Array();
  24872. this.renderSelf = new Array();
  24873. }
  24874. return _InstancesBatch;
  24875. }());
  24876. BABYLON._InstancesBatch = _InstancesBatch;
  24877. var Mesh = /** @class */ (function (_super) {
  24878. __extends(Mesh, _super);
  24879. /**
  24880. * @constructor
  24881. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24882. * @param {Scene} scene The scene to add this mesh to.
  24883. * @param {Node} parent The parent of this mesh, if it has one
  24884. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24885. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24886. * When false, achieved by calling a clone(), also passing False.
  24887. * This will make creation of children, recursive.
  24888. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24889. */
  24890. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24891. if (scene === void 0) { scene = null; }
  24892. if (parent === void 0) { parent = null; }
  24893. if (source === void 0) { source = null; }
  24894. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24895. var _this = _super.call(this, name, scene) || this;
  24896. // Events
  24897. /**
  24898. * An event triggered before rendering the mesh
  24899. * @type {BABYLON.Observable}
  24900. */
  24901. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24902. /**
  24903. * An event triggered after rendering the mesh
  24904. * @type {BABYLON.Observable}
  24905. */
  24906. _this.onAfterRenderObservable = new BABYLON.Observable();
  24907. /**
  24908. * An event triggered before drawing the mesh
  24909. * @type {BABYLON.Observable}
  24910. */
  24911. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24912. // Members
  24913. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24914. _this.instances = new Array();
  24915. _this._LODLevels = new Array();
  24916. _this._visibleInstances = {};
  24917. _this._renderIdForInstances = new Array();
  24918. _this._batchCache = new _InstancesBatch();
  24919. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24920. // Use by builder only to know what orientation were the mesh build in.
  24921. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24922. _this.overrideMaterialSideOrientation = null;
  24923. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24924. // Will be used to save a source mesh reference, If any
  24925. _this._source = null;
  24926. scene = _this.getScene();
  24927. if (source) {
  24928. // Source mesh
  24929. _this._source = source;
  24930. // Geometry
  24931. if (source._geometry) {
  24932. source._geometry.applyToMesh(_this);
  24933. }
  24934. // Deep copy
  24935. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24936. // Metadata
  24937. if (source.metadata && source.metadata.clone) {
  24938. _this.metadata = source.metadata.clone();
  24939. }
  24940. else {
  24941. _this.metadata = source.metadata;
  24942. }
  24943. // Tags
  24944. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24945. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24946. }
  24947. // Parent
  24948. _this.parent = source.parent;
  24949. // Pivot
  24950. _this.setPivotMatrix(source.getPivotMatrix());
  24951. _this.id = name + "." + source.id;
  24952. // Material
  24953. _this.material = source.material;
  24954. var index;
  24955. if (!doNotCloneChildren) {
  24956. // Children
  24957. var directDescendants = source.getDescendants(true);
  24958. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24959. var child = directDescendants[index_1];
  24960. if (child.clone) {
  24961. child.clone(name + "." + child.name, _this);
  24962. }
  24963. }
  24964. }
  24965. // Physics clone
  24966. var physicsEngine = _this.getScene().getPhysicsEngine();
  24967. if (clonePhysicsImpostor && physicsEngine) {
  24968. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24969. if (impostor) {
  24970. _this.physicsImpostor = impostor.clone(_this);
  24971. }
  24972. }
  24973. // Particles
  24974. for (index = 0; index < scene.particleSystems.length; index++) {
  24975. var system = scene.particleSystems[index];
  24976. if (system.emitter === source) {
  24977. system.clone(system.name, _this);
  24978. }
  24979. }
  24980. _this.computeWorldMatrix(true);
  24981. }
  24982. // Parent
  24983. if (parent !== null) {
  24984. _this.parent = parent;
  24985. }
  24986. return _this;
  24987. }
  24988. Object.defineProperty(Mesh, "FRONTSIDE", {
  24989. /**
  24990. * Mesh side orientation : usually the external or front surface
  24991. */
  24992. get: function () {
  24993. return Mesh._FRONTSIDE;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. Object.defineProperty(Mesh, "BACKSIDE", {
  24999. /**
  25000. * Mesh side orientation : usually the internal or back surface
  25001. */
  25002. get: function () {
  25003. return Mesh._BACKSIDE;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25009. /**
  25010. * Mesh side orientation : both internal and external or front and back surfaces
  25011. */
  25012. get: function () {
  25013. return Mesh._DOUBLESIDE;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25019. /**
  25020. * Mesh side orientation : by default, `FRONTSIDE`
  25021. */
  25022. get: function () {
  25023. return Mesh._DEFAULTSIDE;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Object.defineProperty(Mesh, "NO_CAP", {
  25029. /**
  25030. * Mesh cap setting : no cap
  25031. */
  25032. get: function () {
  25033. return Mesh._NO_CAP;
  25034. },
  25035. enumerable: true,
  25036. configurable: true
  25037. });
  25038. Object.defineProperty(Mesh, "CAP_START", {
  25039. /**
  25040. * Mesh cap setting : one cap at the beginning of the mesh
  25041. */
  25042. get: function () {
  25043. return Mesh._CAP_START;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. Object.defineProperty(Mesh, "CAP_END", {
  25049. /**
  25050. * Mesh cap setting : one cap at the end of the mesh
  25051. */
  25052. get: function () {
  25053. return Mesh._CAP_END;
  25054. },
  25055. enumerable: true,
  25056. configurable: true
  25057. });
  25058. Object.defineProperty(Mesh, "CAP_ALL", {
  25059. /**
  25060. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25061. */
  25062. get: function () {
  25063. return Mesh._CAP_ALL;
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25069. set: function (callback) {
  25070. if (this._onBeforeDrawObserver) {
  25071. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25072. }
  25073. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25074. },
  25075. enumerable: true,
  25076. configurable: true
  25077. });
  25078. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25079. get: function () {
  25080. return this._morphTargetManager;
  25081. },
  25082. set: function (value) {
  25083. if (this._morphTargetManager === value) {
  25084. return;
  25085. }
  25086. this._morphTargetManager = value;
  25087. this._syncGeometryWithMorphTargetManager();
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. Object.defineProperty(Mesh.prototype, "source", {
  25093. get: function () {
  25094. return this._source;
  25095. },
  25096. enumerable: true,
  25097. configurable: true
  25098. });
  25099. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25100. get: function () {
  25101. return this._unIndexed;
  25102. },
  25103. set: function (value) {
  25104. if (this._unIndexed !== value) {
  25105. this._unIndexed = value;
  25106. this._markSubMeshesAsAttributesDirty();
  25107. }
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. // Methods
  25113. /**
  25114. * Returns the string "Mesh".
  25115. */
  25116. Mesh.prototype.getClassName = function () {
  25117. return "Mesh";
  25118. };
  25119. /**
  25120. * Returns a string.
  25121. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25122. */
  25123. Mesh.prototype.toString = function (fullDetails) {
  25124. var ret = _super.prototype.toString.call(this, fullDetails);
  25125. ret += ", n vertices: " + this.getTotalVertices();
  25126. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25127. if (this.animations) {
  25128. for (var i = 0; i < this.animations.length; i++) {
  25129. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25130. }
  25131. }
  25132. if (fullDetails) {
  25133. if (this._geometry) {
  25134. var ib = this.getIndices();
  25135. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25136. if (vb && ib) {
  25137. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25138. }
  25139. }
  25140. else {
  25141. ret += ", flat shading: UNKNOWN";
  25142. }
  25143. }
  25144. return ret;
  25145. };
  25146. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25147. /**
  25148. * True if the mesh has some Levels Of Details (LOD).
  25149. * Returns a boolean.
  25150. */
  25151. get: function () {
  25152. return this._LODLevels.length > 0;
  25153. },
  25154. enumerable: true,
  25155. configurable: true
  25156. });
  25157. Mesh.prototype._sortLODLevels = function () {
  25158. this._LODLevels.sort(function (a, b) {
  25159. if (a.distance < b.distance) {
  25160. return 1;
  25161. }
  25162. if (a.distance > b.distance) {
  25163. return -1;
  25164. }
  25165. return 0;
  25166. });
  25167. };
  25168. /**
  25169. * Add a mesh as LOD level triggered at the given distance.
  25170. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25171. * @param {number} distance The distance from the center of the object to show this level
  25172. * @param {Mesh} mesh The mesh to be added as LOD level
  25173. * @return {Mesh} This mesh (for chaining)
  25174. */
  25175. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25176. if (mesh && mesh._masterMesh) {
  25177. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25178. return this;
  25179. }
  25180. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25181. this._LODLevels.push(level);
  25182. if (mesh) {
  25183. mesh._masterMesh = this;
  25184. }
  25185. this._sortLODLevels();
  25186. return this;
  25187. };
  25188. /**
  25189. * Returns the LOD level mesh at the passed distance or null if not found.
  25190. * It is related to the method `addLODLevel(distance, mesh)`.
  25191. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25192. * Returns an object Mesh or `null`.
  25193. */
  25194. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25195. for (var index = 0; index < this._LODLevels.length; index++) {
  25196. var level = this._LODLevels[index];
  25197. if (level.distance === distance) {
  25198. return level.mesh;
  25199. }
  25200. }
  25201. return null;
  25202. };
  25203. /**
  25204. * Remove a mesh from the LOD array
  25205. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25206. * @param {Mesh} mesh The mesh to be removed.
  25207. * @return {Mesh} This mesh (for chaining)
  25208. */
  25209. Mesh.prototype.removeLODLevel = function (mesh) {
  25210. for (var index = 0; index < this._LODLevels.length; index++) {
  25211. if (this._LODLevels[index].mesh === mesh) {
  25212. this._LODLevels.splice(index, 1);
  25213. if (mesh) {
  25214. mesh._masterMesh = null;
  25215. }
  25216. }
  25217. }
  25218. this._sortLODLevels();
  25219. return this;
  25220. };
  25221. /**
  25222. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25223. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25224. */
  25225. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25226. if (!this._LODLevels || this._LODLevels.length === 0) {
  25227. return this;
  25228. }
  25229. var bSphere;
  25230. if (boundingSphere) {
  25231. bSphere = boundingSphere;
  25232. }
  25233. else {
  25234. var boundingInfo = this.getBoundingInfo();
  25235. bSphere = boundingInfo.boundingSphere;
  25236. }
  25237. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25238. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25239. if (this.onLODLevelSelection) {
  25240. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25241. }
  25242. return this;
  25243. }
  25244. for (var index = 0; index < this._LODLevels.length; index++) {
  25245. var level = this._LODLevels[index];
  25246. if (level.distance < distanceToCamera) {
  25247. if (level.mesh) {
  25248. level.mesh._preActivate();
  25249. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25250. }
  25251. if (this.onLODLevelSelection) {
  25252. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25253. }
  25254. return level.mesh;
  25255. }
  25256. }
  25257. if (this.onLODLevelSelection) {
  25258. this.onLODLevelSelection(distanceToCamera, this, this);
  25259. }
  25260. return this;
  25261. };
  25262. Object.defineProperty(Mesh.prototype, "geometry", {
  25263. /**
  25264. * Returns the mesh internal Geometry object.
  25265. */
  25266. get: function () {
  25267. return this._geometry;
  25268. },
  25269. enumerable: true,
  25270. configurable: true
  25271. });
  25272. /**
  25273. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25274. */
  25275. Mesh.prototype.getTotalVertices = function () {
  25276. if (this._geometry === null || this._geometry === undefined) {
  25277. return 0;
  25278. }
  25279. return this._geometry.getTotalVertices();
  25280. };
  25281. /**
  25282. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25283. * 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.
  25284. * You can force the copy with forceCopy === true
  25285. * Returns null if the mesh has no geometry or no vertex buffer.
  25286. * Possible `kind` values :
  25287. * - BABYLON.VertexBuffer.PositionKind
  25288. * - BABYLON.VertexBuffer.UVKind
  25289. * - BABYLON.VertexBuffer.UV2Kind
  25290. * - BABYLON.VertexBuffer.UV3Kind
  25291. * - BABYLON.VertexBuffer.UV4Kind
  25292. * - BABYLON.VertexBuffer.UV5Kind
  25293. * - BABYLON.VertexBuffer.UV6Kind
  25294. * - BABYLON.VertexBuffer.ColorKind
  25295. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25296. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25297. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25298. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25299. */
  25300. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25301. if (!this._geometry) {
  25302. return null;
  25303. }
  25304. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25305. };
  25306. /**
  25307. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25308. * Returns `null` if the mesh has no geometry.
  25309. * Possible `kind` values :
  25310. * - BABYLON.VertexBuffer.PositionKind
  25311. * - BABYLON.VertexBuffer.UVKind
  25312. * - BABYLON.VertexBuffer.UV2Kind
  25313. * - BABYLON.VertexBuffer.UV3Kind
  25314. * - BABYLON.VertexBuffer.UV4Kind
  25315. * - BABYLON.VertexBuffer.UV5Kind
  25316. * - BABYLON.VertexBuffer.UV6Kind
  25317. * - BABYLON.VertexBuffer.ColorKind
  25318. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25319. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25320. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25321. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25322. */
  25323. Mesh.prototype.getVertexBuffer = function (kind) {
  25324. if (!this._geometry) {
  25325. return null;
  25326. }
  25327. return this._geometry.getVertexBuffer(kind);
  25328. };
  25329. /**
  25330. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25331. * Possible `kind` values :
  25332. * - BABYLON.VertexBuffer.PositionKind
  25333. * - BABYLON.VertexBuffer.UVKind
  25334. * - BABYLON.VertexBuffer.UV2Kind
  25335. * - BABYLON.VertexBuffer.UV3Kind
  25336. * - BABYLON.VertexBuffer.UV4Kind
  25337. * - BABYLON.VertexBuffer.UV5Kind
  25338. * - BABYLON.VertexBuffer.UV6Kind
  25339. * - BABYLON.VertexBuffer.ColorKind
  25340. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25341. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25342. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25343. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25344. */
  25345. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25346. if (!this._geometry) {
  25347. if (this._delayInfo) {
  25348. return this._delayInfo.indexOf(kind) !== -1;
  25349. }
  25350. return false;
  25351. }
  25352. return this._geometry.isVerticesDataPresent(kind);
  25353. };
  25354. /**
  25355. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25356. * Possible `kind` values :
  25357. * - BABYLON.VertexBuffer.PositionKind
  25358. * - BABYLON.VertexBuffer.UVKind
  25359. * - BABYLON.VertexBuffer.UV2Kind
  25360. * - BABYLON.VertexBuffer.UV3Kind
  25361. * - BABYLON.VertexBuffer.UV4Kind
  25362. * - BABYLON.VertexBuffer.UV5Kind
  25363. * - BABYLON.VertexBuffer.UV6Kind
  25364. * - BABYLON.VertexBuffer.ColorKind
  25365. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25366. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25367. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25368. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25369. */
  25370. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25371. if (!this._geometry) {
  25372. if (this._delayInfo) {
  25373. return this._delayInfo.indexOf(kind) !== -1;
  25374. }
  25375. return false;
  25376. }
  25377. return this._geometry.isVertexBufferUpdatable(kind);
  25378. };
  25379. /**
  25380. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25381. * Possible `kind` values :
  25382. * - BABYLON.VertexBuffer.PositionKind
  25383. * - BABYLON.VertexBuffer.UVKind
  25384. * - BABYLON.VertexBuffer.UV2Kind
  25385. * - BABYLON.VertexBuffer.UV3Kind
  25386. * - BABYLON.VertexBuffer.UV4Kind
  25387. * - BABYLON.VertexBuffer.UV5Kind
  25388. * - BABYLON.VertexBuffer.UV6Kind
  25389. * - BABYLON.VertexBuffer.ColorKind
  25390. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25391. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25392. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25393. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25394. */
  25395. Mesh.prototype.getVerticesDataKinds = function () {
  25396. if (!this._geometry) {
  25397. var result = new Array();
  25398. if (this._delayInfo) {
  25399. this._delayInfo.forEach(function (kind, index, array) {
  25400. result.push(kind);
  25401. });
  25402. }
  25403. return result;
  25404. }
  25405. return this._geometry.getVerticesDataKinds();
  25406. };
  25407. /**
  25408. * Returns a positive integer : the total number of indices in this mesh geometry.
  25409. * Returns zero if the mesh has no geometry.
  25410. */
  25411. Mesh.prototype.getTotalIndices = function () {
  25412. if (!this._geometry) {
  25413. return 0;
  25414. }
  25415. return this._geometry.getTotalIndices();
  25416. };
  25417. /**
  25418. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25419. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  25420. * Returns an empty array if the mesh has no geometry.
  25421. */
  25422. Mesh.prototype.getIndices = function (copyWhenShared) {
  25423. if (!this._geometry) {
  25424. return [];
  25425. }
  25426. return this._geometry.getIndices(copyWhenShared);
  25427. };
  25428. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25429. get: function () {
  25430. return this._masterMesh !== null && this._masterMesh !== undefined;
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. /**
  25436. * Determine if the current mesh is ready to be rendered
  25437. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25438. * @returns true if all associated assets are ready (material, textures, shaders)
  25439. */
  25440. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25441. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25442. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25443. return false;
  25444. }
  25445. if (!_super.prototype.isReady.call(this)) {
  25446. return false;
  25447. }
  25448. if (!this.subMeshes || this.subMeshes.length === 0) {
  25449. return true;
  25450. }
  25451. var engine = this.getEngine();
  25452. var scene = this.getScene();
  25453. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25454. this.computeWorldMatrix();
  25455. var mat = this.material || scene.defaultMaterial;
  25456. if (mat) {
  25457. if (mat.storeEffectOnSubMeshes) {
  25458. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25459. var subMesh = _a[_i];
  25460. var effectiveMaterial = subMesh.getMaterial();
  25461. if (effectiveMaterial) {
  25462. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25463. return false;
  25464. }
  25465. }
  25466. }
  25467. }
  25468. else {
  25469. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25470. return false;
  25471. }
  25472. }
  25473. }
  25474. // Shadows
  25475. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25476. var light = _c[_b];
  25477. var generator = light.getShadowGenerator();
  25478. if (generator) {
  25479. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25480. var subMesh = _e[_d];
  25481. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25482. return false;
  25483. }
  25484. }
  25485. }
  25486. }
  25487. // LOD
  25488. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25489. var lod = _g[_f];
  25490. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25491. return false;
  25492. }
  25493. }
  25494. return true;
  25495. };
  25496. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25497. /**
  25498. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25499. * This property is pertinent only for updatable parametric shapes.
  25500. */
  25501. get: function () {
  25502. return this._areNormalsFrozen;
  25503. },
  25504. enumerable: true,
  25505. configurable: true
  25506. });
  25507. /**
  25508. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25509. * It has no effect at all on other shapes.
  25510. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25511. * Returns the Mesh.
  25512. */
  25513. Mesh.prototype.freezeNormals = function () {
  25514. this._areNormalsFrozen = true;
  25515. return this;
  25516. };
  25517. /**
  25518. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25519. * It has no effect at all on other shapes.
  25520. * It reactivates the mesh normals computation if it was previously frozen.
  25521. * Returns the Mesh.
  25522. */
  25523. Mesh.prototype.unfreezeNormals = function () {
  25524. this._areNormalsFrozen = false;
  25525. return this;
  25526. };
  25527. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25528. /**
  25529. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25530. */
  25531. set: function (count) {
  25532. this._overridenInstanceCount = count;
  25533. },
  25534. enumerable: true,
  25535. configurable: true
  25536. });
  25537. // Methods
  25538. Mesh.prototype._preActivate = function () {
  25539. var sceneRenderId = this.getScene().getRenderId();
  25540. if (this._preActivateId === sceneRenderId) {
  25541. return this;
  25542. }
  25543. this._preActivateId = sceneRenderId;
  25544. this._visibleInstances = null;
  25545. return this;
  25546. };
  25547. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25548. if (this._visibleInstances) {
  25549. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25550. }
  25551. return this;
  25552. };
  25553. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25554. if (!this._visibleInstances) {
  25555. this._visibleInstances = {};
  25556. this._visibleInstances.defaultRenderId = renderId;
  25557. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25558. }
  25559. if (!this._visibleInstances[renderId]) {
  25560. this._visibleInstances[renderId] = new Array();
  25561. }
  25562. this._visibleInstances[renderId].push(instance);
  25563. return this;
  25564. };
  25565. /**
  25566. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25567. * This means the mesh underlying bounding box and sphere are recomputed.
  25568. * Returns the Mesh.
  25569. */
  25570. Mesh.prototype.refreshBoundingInfo = function () {
  25571. return this._refreshBoundingInfo(false);
  25572. };
  25573. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25574. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25575. return this;
  25576. }
  25577. var data = this._getPositionData(applySkeleton);
  25578. if (data) {
  25579. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25580. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25581. }
  25582. if (this.subMeshes) {
  25583. for (var index = 0; index < this.subMeshes.length; index++) {
  25584. this.subMeshes[index].refreshBoundingInfo();
  25585. }
  25586. }
  25587. this._updateBoundingInfo();
  25588. return this;
  25589. };
  25590. Mesh.prototype._getPositionData = function (applySkeleton) {
  25591. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25592. if (data && applySkeleton && this.skeleton) {
  25593. data = data.slice();
  25594. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25595. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25596. if (matricesWeightsData && matricesIndicesData) {
  25597. var needExtras = this.numBoneInfluencers > 4;
  25598. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25599. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25600. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25601. var tempVector = BABYLON.Tmp.Vector3[0];
  25602. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25603. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25604. var matWeightIdx = 0;
  25605. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25606. finalMatrix.reset();
  25607. var inf;
  25608. var weight;
  25609. for (inf = 0; inf < 4; inf++) {
  25610. weight = matricesWeightsData[matWeightIdx + inf];
  25611. if (weight <= 0)
  25612. break;
  25613. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25614. finalMatrix.addToSelf(tempMatrix);
  25615. }
  25616. if (needExtras) {
  25617. for (inf = 0; inf < 4; inf++) {
  25618. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25619. if (weight <= 0)
  25620. break;
  25621. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25622. finalMatrix.addToSelf(tempMatrix);
  25623. }
  25624. }
  25625. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25626. tempVector.toArray(data, index);
  25627. }
  25628. }
  25629. }
  25630. return data;
  25631. };
  25632. Mesh.prototype._createGlobalSubMesh = function (force) {
  25633. var totalVertices = this.getTotalVertices();
  25634. if (!totalVertices || !this.getIndices()) {
  25635. return null;
  25636. }
  25637. // Check if we need to recreate the submeshes
  25638. if (this.subMeshes && this.subMeshes.length > 0) {
  25639. var ib = this.getIndices();
  25640. if (!ib) {
  25641. return null;
  25642. }
  25643. var totalIndices = ib.length;
  25644. var needToRecreate = false;
  25645. if (force) {
  25646. needToRecreate = true;
  25647. }
  25648. else {
  25649. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25650. var submesh = _a[_i];
  25651. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25652. needToRecreate = true;
  25653. break;
  25654. }
  25655. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25656. needToRecreate = true;
  25657. break;
  25658. }
  25659. }
  25660. }
  25661. if (!needToRecreate) {
  25662. return this.subMeshes[0];
  25663. }
  25664. }
  25665. this.releaseSubMeshes();
  25666. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25667. };
  25668. Mesh.prototype.subdivide = function (count) {
  25669. if (count < 1) {
  25670. return;
  25671. }
  25672. var totalIndices = this.getTotalIndices();
  25673. var subdivisionSize = (totalIndices / count) | 0;
  25674. var offset = 0;
  25675. // Ensure that subdivisionSize is a multiple of 3
  25676. while (subdivisionSize % 3 !== 0) {
  25677. subdivisionSize++;
  25678. }
  25679. this.releaseSubMeshes();
  25680. for (var index = 0; index < count; index++) {
  25681. if (offset >= totalIndices) {
  25682. break;
  25683. }
  25684. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25685. offset += subdivisionSize;
  25686. }
  25687. this.synchronizeInstances();
  25688. };
  25689. /**
  25690. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25691. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25692. * The `data` are either a numeric array either a Float32Array.
  25693. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25694. * 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).
  25695. * Note that a new underlying VertexBuffer object is created each call.
  25696. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25697. *
  25698. * Possible `kind` values :
  25699. * - BABYLON.VertexBuffer.PositionKind
  25700. * - BABYLON.VertexBuffer.UVKind
  25701. * - BABYLON.VertexBuffer.UV2Kind
  25702. * - BABYLON.VertexBuffer.UV3Kind
  25703. * - BABYLON.VertexBuffer.UV4Kind
  25704. * - BABYLON.VertexBuffer.UV5Kind
  25705. * - BABYLON.VertexBuffer.UV6Kind
  25706. * - BABYLON.VertexBuffer.ColorKind
  25707. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25708. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25709. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25710. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25711. *
  25712. * Returns the Mesh.
  25713. */
  25714. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25715. if (updatable === void 0) { updatable = false; }
  25716. if (!this._geometry) {
  25717. var vertexData = new BABYLON.VertexData();
  25718. vertexData.set(data, kind);
  25719. var scene = this.getScene();
  25720. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25721. }
  25722. else {
  25723. this._geometry.setVerticesData(kind, data, updatable, stride);
  25724. }
  25725. return this;
  25726. };
  25727. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25728. if (updatable === void 0) { updatable = true; }
  25729. var vb = this.getVertexBuffer(kind);
  25730. if (!vb || vb.isUpdatable() === updatable) {
  25731. return;
  25732. }
  25733. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25734. };
  25735. /**
  25736. * Sets the mesh VertexBuffer.
  25737. * Returns the Mesh.
  25738. */
  25739. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25740. if (!this._geometry) {
  25741. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25742. }
  25743. this._geometry.setVerticesBuffer(buffer);
  25744. return this;
  25745. };
  25746. /**
  25747. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25748. * If the mesh has no geometry, it is simply returned as it is.
  25749. * The `data` are either a numeric array either a Float32Array.
  25750. * No new underlying VertexBuffer object is created.
  25751. * 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.
  25752. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25753. *
  25754. * Possible `kind` values :
  25755. * - BABYLON.VertexBuffer.PositionKind
  25756. * - BABYLON.VertexBuffer.UVKind
  25757. * - BABYLON.VertexBuffer.UV2Kind
  25758. * - BABYLON.VertexBuffer.UV3Kind
  25759. * - BABYLON.VertexBuffer.UV4Kind
  25760. * - BABYLON.VertexBuffer.UV5Kind
  25761. * - BABYLON.VertexBuffer.UV6Kind
  25762. * - BABYLON.VertexBuffer.ColorKind
  25763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25767. *
  25768. * Returns the Mesh.
  25769. */
  25770. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25771. if (!this._geometry) {
  25772. return this;
  25773. }
  25774. if (!makeItUnique) {
  25775. this._geometry.updateVerticesData(kind, data, updateExtends);
  25776. }
  25777. else {
  25778. this.makeGeometryUnique();
  25779. this.updateVerticesData(kind, data, updateExtends, false);
  25780. }
  25781. return this;
  25782. };
  25783. /**
  25784. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25785. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25786. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25787. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25788. * Returns the Mesh.
  25789. */
  25790. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25791. if (computeNormals === void 0) { computeNormals = true; }
  25792. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25793. if (!positions) {
  25794. return this;
  25795. }
  25796. positionFunction(positions);
  25797. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25798. if (computeNormals) {
  25799. var indices = this.getIndices();
  25800. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25801. if (!normals) {
  25802. return this;
  25803. }
  25804. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25805. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25806. }
  25807. return this;
  25808. };
  25809. /**
  25810. * Creates a un-shared specific occurence of the geometry for the mesh.
  25811. * Returns the Mesh.
  25812. */
  25813. Mesh.prototype.makeGeometryUnique = function () {
  25814. if (!this._geometry) {
  25815. return this;
  25816. }
  25817. var oldGeometry = this._geometry;
  25818. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25819. oldGeometry.releaseForMesh(this, true);
  25820. geometry.applyToMesh(this);
  25821. return this;
  25822. };
  25823. /**
  25824. * Sets the mesh indices.
  25825. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25826. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25827. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25828. * This method creates a new index buffer each call.
  25829. * Returns the Mesh.
  25830. */
  25831. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25832. if (totalVertices === void 0) { totalVertices = null; }
  25833. if (updatable === void 0) { updatable = false; }
  25834. if (!this._geometry) {
  25835. var vertexData = new BABYLON.VertexData();
  25836. vertexData.indices = indices;
  25837. var scene = this.getScene();
  25838. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25839. }
  25840. else {
  25841. this._geometry.setIndices(indices, totalVertices, updatable);
  25842. }
  25843. return this;
  25844. };
  25845. /**
  25846. * Update the current index buffer
  25847. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25848. * Returns the Mesh.
  25849. */
  25850. Mesh.prototype.updateIndices = function (indices, offset) {
  25851. if (!this._geometry) {
  25852. return this;
  25853. }
  25854. this._geometry.updateIndices(indices, offset);
  25855. return this;
  25856. };
  25857. /**
  25858. * Invert the geometry to move from a right handed system to a left handed one.
  25859. * Returns the Mesh.
  25860. */
  25861. Mesh.prototype.toLeftHanded = function () {
  25862. if (!this._geometry) {
  25863. return this;
  25864. }
  25865. this._geometry.toLeftHanded();
  25866. return this;
  25867. };
  25868. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25869. if (!this._geometry) {
  25870. return this;
  25871. }
  25872. var engine = this.getScene().getEngine();
  25873. // Wireframe
  25874. var indexToBind;
  25875. if (this._unIndexed) {
  25876. indexToBind = null;
  25877. }
  25878. else {
  25879. switch (fillMode) {
  25880. case BABYLON.Material.PointFillMode:
  25881. indexToBind = null;
  25882. break;
  25883. case BABYLON.Material.WireFrameFillMode:
  25884. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25885. break;
  25886. default:
  25887. case BABYLON.Material.TriangleFillMode:
  25888. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25889. break;
  25890. }
  25891. }
  25892. // VBOs
  25893. this._geometry._bind(effect, indexToBind);
  25894. return this;
  25895. };
  25896. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25897. if (alternate === void 0) { alternate = false; }
  25898. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25899. return this;
  25900. }
  25901. this.onBeforeDrawObservable.notifyObservers(this);
  25902. var scene = this.getScene();
  25903. var engine = scene.getEngine();
  25904. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25905. // or triangles as points
  25906. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25907. }
  25908. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25909. // Triangles as wireframe
  25910. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25911. }
  25912. else {
  25913. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25914. }
  25915. if (scene._isAlternateRenderingEnabled && !alternate) {
  25916. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25917. if (!effect || !scene.activeCamera) {
  25918. return this;
  25919. }
  25920. scene._switchToAlternateCameraConfiguration(true);
  25921. this._effectiveMaterial.bindView(effect);
  25922. this._effectiveMaterial.bindViewProjection(effect);
  25923. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25924. this._draw(subMesh, fillMode, instancesCount, true);
  25925. engine.setViewport(scene.activeCamera.viewport);
  25926. scene._switchToAlternateCameraConfiguration(false);
  25927. this._effectiveMaterial.bindView(effect);
  25928. this._effectiveMaterial.bindViewProjection(effect);
  25929. }
  25930. return this;
  25931. };
  25932. /**
  25933. * Registers for this mesh a javascript function called just before the rendering process.
  25934. * This function is passed the current mesh.
  25935. * Return the Mesh.
  25936. */
  25937. Mesh.prototype.registerBeforeRender = function (func) {
  25938. this.onBeforeRenderObservable.add(func);
  25939. return this;
  25940. };
  25941. /**
  25942. * Disposes a previously registered javascript function called before the rendering.
  25943. * This function is passed the current mesh.
  25944. * Returns the Mesh.
  25945. */
  25946. Mesh.prototype.unregisterBeforeRender = function (func) {
  25947. this.onBeforeRenderObservable.removeCallback(func);
  25948. return this;
  25949. };
  25950. /**
  25951. * Registers for this mesh a javascript function called just after the rendering is complete.
  25952. * This function is passed the current mesh.
  25953. * Returns the Mesh.
  25954. */
  25955. Mesh.prototype.registerAfterRender = function (func) {
  25956. this.onAfterRenderObservable.add(func);
  25957. return this;
  25958. };
  25959. /**
  25960. * Disposes a previously registered javascript function called after the rendering.
  25961. * This function is passed the current mesh.
  25962. * Return the Mesh.
  25963. */
  25964. Mesh.prototype.unregisterAfterRender = function (func) {
  25965. this.onAfterRenderObservable.removeCallback(func);
  25966. return this;
  25967. };
  25968. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25969. var scene = this.getScene();
  25970. this._batchCache.mustReturn = false;
  25971. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25972. this._batchCache.visibleInstances[subMeshId] = null;
  25973. if (this._visibleInstances) {
  25974. var currentRenderId = scene.getRenderId();
  25975. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25976. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25977. var selfRenderId = this._renderId;
  25978. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25979. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25980. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25981. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25982. }
  25983. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25984. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25985. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25986. this._batchCache.mustReturn = true;
  25987. return this._batchCache;
  25988. }
  25989. if (currentRenderId !== selfRenderId) {
  25990. this._batchCache.renderSelf[subMeshId] = false;
  25991. }
  25992. }
  25993. this._renderIdForInstances[subMeshId] = currentRenderId;
  25994. }
  25995. return this._batchCache;
  25996. };
  25997. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25998. var visibleInstances = batch.visibleInstances[subMesh._id];
  25999. if (!visibleInstances) {
  26000. return this;
  26001. }
  26002. var matricesCount = visibleInstances.length + 1;
  26003. var bufferSize = matricesCount * 16 * 4;
  26004. var currentInstancesBufferSize = this._instancesBufferSize;
  26005. var instancesBuffer = this._instancesBuffer;
  26006. while (this._instancesBufferSize < bufferSize) {
  26007. this._instancesBufferSize *= 2;
  26008. }
  26009. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26010. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26011. }
  26012. var offset = 0;
  26013. var instancesCount = 0;
  26014. var world = this.getWorldMatrix();
  26015. if (batch.renderSelf[subMesh._id]) {
  26016. world.copyToArray(this._instancesData, offset);
  26017. offset += 16;
  26018. instancesCount++;
  26019. }
  26020. if (visibleInstances) {
  26021. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26022. var instance = visibleInstances[instanceIndex];
  26023. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26024. offset += 16;
  26025. instancesCount++;
  26026. }
  26027. }
  26028. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26029. if (instancesBuffer) {
  26030. instancesBuffer.dispose();
  26031. }
  26032. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26033. this._instancesBuffer = instancesBuffer;
  26034. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26035. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26036. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26037. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26038. }
  26039. else {
  26040. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26041. }
  26042. this._bind(subMesh, effect, fillMode);
  26043. this._draw(subMesh, fillMode, instancesCount);
  26044. engine.unbindInstanceAttributes();
  26045. return this;
  26046. };
  26047. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26048. var scene = this.getScene();
  26049. var engine = scene.getEngine();
  26050. if (hardwareInstancedRendering) {
  26051. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26052. }
  26053. else {
  26054. if (batch.renderSelf[subMesh._id]) {
  26055. // Draw
  26056. if (onBeforeDraw) {
  26057. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26058. }
  26059. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26060. }
  26061. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26062. if (visibleInstancesForSubMesh) {
  26063. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26064. var instance = visibleInstancesForSubMesh[instanceIndex];
  26065. // World
  26066. var world = instance.getWorldMatrix();
  26067. if (onBeforeDraw) {
  26068. onBeforeDraw(true, world, effectiveMaterial);
  26069. }
  26070. // Draw
  26071. this._draw(subMesh, fillMode);
  26072. }
  26073. }
  26074. }
  26075. return this;
  26076. };
  26077. /**
  26078. * Triggers the draw call for the mesh.
  26079. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26080. * Returns the Mesh.
  26081. */
  26082. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26083. this.checkOcclusionQuery();
  26084. if (this._isOccluded) {
  26085. return this;
  26086. }
  26087. var scene = this.getScene();
  26088. // Managing instances
  26089. var batch = this._getInstancesRenderList(subMesh._id);
  26090. if (batch.mustReturn) {
  26091. return this;
  26092. }
  26093. // Checking geometry state
  26094. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26095. return this;
  26096. }
  26097. this.onBeforeRenderObservable.notifyObservers(this);
  26098. var engine = scene.getEngine();
  26099. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26100. // Material
  26101. var material = subMesh.getMaterial();
  26102. if (!material) {
  26103. return this;
  26104. }
  26105. this._effectiveMaterial = material;
  26106. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26107. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26108. return this;
  26109. }
  26110. }
  26111. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26112. return this;
  26113. }
  26114. // Alpha mode
  26115. if (enableAlphaMode) {
  26116. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26117. }
  26118. // Outline - step 1
  26119. var savedDepthWrite = engine.getDepthWrite();
  26120. if (this.renderOutline) {
  26121. engine.setDepthWrite(false);
  26122. scene.getOutlineRenderer().render(subMesh, batch);
  26123. engine.setDepthWrite(savedDepthWrite);
  26124. }
  26125. var effect;
  26126. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26127. effect = subMesh.effect;
  26128. }
  26129. else {
  26130. effect = this._effectiveMaterial.getEffect();
  26131. }
  26132. if (!effect) {
  26133. return this;
  26134. }
  26135. var sideOrientation = this.overrideMaterialSideOrientation;
  26136. if (sideOrientation == null) {
  26137. sideOrientation = this._effectiveMaterial.sideOrientation;
  26138. if (this._getWorldMatrixDeterminant() < 0) {
  26139. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26140. }
  26141. }
  26142. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26143. if (this._effectiveMaterial.forceDepthWrite) {
  26144. engine.setDepthWrite(true);
  26145. }
  26146. // Bind
  26147. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26148. if (!hardwareInstancedRendering) {
  26149. this._bind(subMesh, effect, fillMode);
  26150. }
  26151. var world = this.getWorldMatrix();
  26152. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26153. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26154. }
  26155. else {
  26156. this._effectiveMaterial.bind(world, this);
  26157. }
  26158. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26159. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26160. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26161. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26162. }
  26163. // Draw
  26164. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26165. // Unbind
  26166. this._effectiveMaterial.unbind();
  26167. // Outline - step 2
  26168. if (this.renderOutline && savedDepthWrite) {
  26169. engine.setDepthWrite(true);
  26170. engine.setColorWrite(false);
  26171. scene.getOutlineRenderer().render(subMesh, batch);
  26172. engine.setColorWrite(true);
  26173. }
  26174. // Overlay
  26175. if (this.renderOverlay) {
  26176. var currentMode = engine.getAlphaMode();
  26177. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26178. scene.getOutlineRenderer().render(subMesh, batch, true);
  26179. engine.setAlphaMode(currentMode);
  26180. }
  26181. this.onAfterRenderObservable.notifyObservers(this);
  26182. return this;
  26183. };
  26184. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26185. if (isInstance && effectiveMaterial) {
  26186. effectiveMaterial.bindOnlyWorldMatrix(world);
  26187. }
  26188. };
  26189. /**
  26190. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26191. */
  26192. Mesh.prototype.getEmittedParticleSystems = function () {
  26193. var results = new Array();
  26194. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26195. var particleSystem = this.getScene().particleSystems[index];
  26196. if (particleSystem.emitter === this) {
  26197. results.push(particleSystem);
  26198. }
  26199. }
  26200. return results;
  26201. };
  26202. /**
  26203. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26204. */
  26205. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26206. var results = new Array();
  26207. var descendants = this.getDescendants();
  26208. descendants.push(this);
  26209. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26210. var particleSystem = this.getScene().particleSystems[index];
  26211. var emitter = particleSystem.emitter;
  26212. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26213. results.push(particleSystem);
  26214. }
  26215. }
  26216. return results;
  26217. };
  26218. Mesh.prototype._checkDelayState = function () {
  26219. var scene = this.getScene();
  26220. if (this._geometry) {
  26221. this._geometry.load(scene);
  26222. }
  26223. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26225. this._queueLoad(scene);
  26226. }
  26227. return this;
  26228. };
  26229. Mesh.prototype._queueLoad = function (scene) {
  26230. var _this = this;
  26231. scene._addPendingData(this);
  26232. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26233. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26234. if (data instanceof ArrayBuffer) {
  26235. _this._delayLoadingFunction(data, _this);
  26236. }
  26237. else {
  26238. _this._delayLoadingFunction(JSON.parse(data), _this);
  26239. }
  26240. _this.instances.forEach(function (instance) {
  26241. instance._syncSubMeshes();
  26242. });
  26243. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26244. scene._removePendingData(_this);
  26245. }, function () { }, scene.database, getBinaryData);
  26246. return this;
  26247. };
  26248. /**
  26249. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26250. */
  26251. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26252. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26253. return false;
  26254. }
  26255. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26256. return false;
  26257. }
  26258. this._checkDelayState();
  26259. return true;
  26260. };
  26261. /**
  26262. * Sets the mesh material by the material or multiMaterial `id` property.
  26263. * The material `id` is a string identifying the material or the multiMaterial.
  26264. * This method returns the Mesh.
  26265. */
  26266. Mesh.prototype.setMaterialByID = function (id) {
  26267. var materials = this.getScene().materials;
  26268. var index;
  26269. for (index = materials.length - 1; index > -1; index--) {
  26270. if (materials[index].id === id) {
  26271. this.material = materials[index];
  26272. return this;
  26273. }
  26274. }
  26275. // Multi
  26276. var multiMaterials = this.getScene().multiMaterials;
  26277. for (index = multiMaterials.length - 1; index > -1; index--) {
  26278. if (multiMaterials[index].id === id) {
  26279. this.material = multiMaterials[index];
  26280. return this;
  26281. }
  26282. }
  26283. return this;
  26284. };
  26285. /**
  26286. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26287. */
  26288. Mesh.prototype.getAnimatables = function () {
  26289. var results = new Array();
  26290. if (this.material) {
  26291. results.push(this.material);
  26292. }
  26293. if (this.skeleton) {
  26294. results.push(this.skeleton);
  26295. }
  26296. return results;
  26297. };
  26298. /**
  26299. * Modifies the mesh geometry according to the passed transformation matrix.
  26300. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26301. * The mesh normals are modified accordingly the same transformation.
  26302. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26303. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26304. * Returns the Mesh.
  26305. */
  26306. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26307. // Position
  26308. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26309. return this;
  26310. }
  26311. var submeshes = this.subMeshes.splice(0);
  26312. this._resetPointsArrayCache();
  26313. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26314. var temp = new Array();
  26315. var index;
  26316. for (index = 0; index < data.length; index += 3) {
  26317. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26318. }
  26319. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26320. // Normals
  26321. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26322. return this;
  26323. }
  26324. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26325. temp = [];
  26326. for (index = 0; index < data.length; index += 3) {
  26327. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26328. }
  26329. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26330. // flip faces?
  26331. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26332. this.flipFaces();
  26333. }
  26334. // Restore submeshes
  26335. this.releaseSubMeshes();
  26336. this.subMeshes = submeshes;
  26337. return this;
  26338. };
  26339. /**
  26340. * Modifies the mesh geometry according to its own current World Matrix.
  26341. * The mesh World Matrix is then reset.
  26342. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26343. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26344. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26345. * Returns the Mesh.
  26346. */
  26347. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26348. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26349. this.scaling.copyFromFloats(1, 1, 1);
  26350. this.position.copyFromFloats(0, 0, 0);
  26351. this.rotation.copyFromFloats(0, 0, 0);
  26352. //only if quaternion is already set
  26353. if (this.rotationQuaternion) {
  26354. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26355. }
  26356. this._worldMatrix = BABYLON.Matrix.Identity();
  26357. return this;
  26358. };
  26359. Object.defineProperty(Mesh.prototype, "_positions", {
  26360. // Cache
  26361. get: function () {
  26362. if (this._geometry) {
  26363. return this._geometry._positions;
  26364. }
  26365. return null;
  26366. },
  26367. enumerable: true,
  26368. configurable: true
  26369. });
  26370. Mesh.prototype._resetPointsArrayCache = function () {
  26371. if (this._geometry) {
  26372. this._geometry._resetPointsArrayCache();
  26373. }
  26374. return this;
  26375. };
  26376. Mesh.prototype._generatePointsArray = function () {
  26377. if (this._geometry) {
  26378. return this._geometry._generatePointsArray();
  26379. }
  26380. return false;
  26381. };
  26382. /**
  26383. * Returns a new Mesh object generated from the current mesh properties.
  26384. * This method must not get confused with createInstance().
  26385. * The parameter `name` is a string, the name given to the new mesh.
  26386. * The optional parameter `newParent` can be any Node object (default `null`).
  26387. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26388. * 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.
  26389. */
  26390. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26391. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26392. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26393. };
  26394. /**
  26395. * Disposes the Mesh.
  26396. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26397. * Returns nothing.
  26398. */
  26399. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26400. var _this = this;
  26401. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26402. this.morphTargetManager = null;
  26403. if (this._geometry) {
  26404. this._geometry.releaseForMesh(this, true);
  26405. }
  26406. // Sources
  26407. var meshes = this.getScene().meshes;
  26408. meshes.forEach(function (abstractMesh) {
  26409. var mesh = abstractMesh;
  26410. if (mesh._source && mesh._source === _this) {
  26411. mesh._source = null;
  26412. }
  26413. });
  26414. this._source = null;
  26415. // Instances
  26416. if (this._instancesBuffer) {
  26417. this._instancesBuffer.dispose();
  26418. this._instancesBuffer = null;
  26419. }
  26420. while (this.instances.length) {
  26421. this.instances[0].dispose();
  26422. }
  26423. // Highlight layers.
  26424. var highlightLayers = this.getScene().highlightLayers;
  26425. for (var i = 0; i < highlightLayers.length; i++) {
  26426. var highlightLayer = highlightLayers[i];
  26427. if (highlightLayer) {
  26428. highlightLayer.removeMesh(this);
  26429. highlightLayer.removeExcludedMesh(this);
  26430. }
  26431. }
  26432. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26433. };
  26434. /**
  26435. * Modifies the mesh geometry according to a displacement map.
  26436. * 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.
  26437. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26438. * This method returns nothing.
  26439. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26440. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26441. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  26442. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26443. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26444. *
  26445. * Returns the Mesh.
  26446. */
  26447. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26448. var _this = this;
  26449. var scene = this.getScene();
  26450. var onload = function (img) {
  26451. // Getting height map data
  26452. var canvas = document.createElement("canvas");
  26453. var context = canvas.getContext("2d");
  26454. var heightMapWidth = img.width;
  26455. var heightMapHeight = img.height;
  26456. canvas.width = heightMapWidth;
  26457. canvas.height = heightMapHeight;
  26458. context.drawImage(img, 0, 0);
  26459. // Create VertexData from map data
  26460. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26461. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26462. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26463. //execute success callback, if set
  26464. if (onSuccess) {
  26465. onSuccess(_this);
  26466. }
  26467. };
  26468. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26469. return this;
  26470. };
  26471. /**
  26472. * Modifies the mesh geometry according to a displacementMap buffer.
  26473. * 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.
  26474. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26475. * This method returns nothing.
  26476. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  26477. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26478. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26479. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26480. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26481. *
  26482. * Returns the Mesh.
  26483. */
  26484. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26485. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26486. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26487. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26488. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26489. return this;
  26490. }
  26491. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26492. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26493. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26494. var position = BABYLON.Vector3.Zero();
  26495. var normal = BABYLON.Vector3.Zero();
  26496. var uv = BABYLON.Vector2.Zero();
  26497. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26498. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26499. for (var index = 0; index < positions.length; index += 3) {
  26500. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26501. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26502. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26503. // Compute height
  26504. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26505. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26506. var pos = (u + v * heightMapWidth) * 4;
  26507. var r = buffer[pos] / 255.0;
  26508. var g = buffer[pos + 1] / 255.0;
  26509. var b = buffer[pos + 2] / 255.0;
  26510. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26511. normal.normalize();
  26512. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26513. position = position.add(normal);
  26514. position.toArray(positions, index);
  26515. }
  26516. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26517. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26518. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26519. return this;
  26520. };
  26521. /**
  26522. * Modify the mesh to get a flat shading rendering.
  26523. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26524. * This method returns the Mesh.
  26525. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26526. */
  26527. Mesh.prototype.convertToFlatShadedMesh = function () {
  26528. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26529. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26530. var kinds = this.getVerticesDataKinds();
  26531. var vbs = {};
  26532. var data = {};
  26533. var newdata = {};
  26534. var updatableNormals = false;
  26535. var kindIndex;
  26536. var kind;
  26537. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26538. kind = kinds[kindIndex];
  26539. var vertexBuffer = this.getVertexBuffer(kind);
  26540. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26541. updatableNormals = vertexBuffer.isUpdatable();
  26542. kinds.splice(kindIndex, 1);
  26543. kindIndex--;
  26544. continue;
  26545. }
  26546. vbs[kind] = vertexBuffer;
  26547. data[kind] = vbs[kind].getData();
  26548. newdata[kind] = [];
  26549. }
  26550. // Save previous submeshes
  26551. var previousSubmeshes = this.subMeshes.slice(0);
  26552. var indices = this.getIndices();
  26553. var totalIndices = this.getTotalIndices();
  26554. // Generating unique vertices per face
  26555. var index;
  26556. for (index = 0; index < totalIndices; index++) {
  26557. var vertexIndex = indices[index];
  26558. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26559. kind = kinds[kindIndex];
  26560. var stride = vbs[kind].getStrideSize();
  26561. for (var offset = 0; offset < stride; offset++) {
  26562. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26563. }
  26564. }
  26565. }
  26566. // Updating faces & normal
  26567. var normals = [];
  26568. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26569. for (index = 0; index < totalIndices; index += 3) {
  26570. indices[index] = index;
  26571. indices[index + 1] = index + 1;
  26572. indices[index + 2] = index + 2;
  26573. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26574. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26575. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26576. var p1p2 = p1.subtract(p2);
  26577. var p3p2 = p3.subtract(p2);
  26578. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26579. // Store same normals for every vertex
  26580. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26581. normals.push(normal.x);
  26582. normals.push(normal.y);
  26583. normals.push(normal.z);
  26584. }
  26585. }
  26586. this.setIndices(indices);
  26587. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26588. // Updating vertex buffers
  26589. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26590. kind = kinds[kindIndex];
  26591. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26592. }
  26593. // Updating submeshes
  26594. this.releaseSubMeshes();
  26595. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26596. var previousOne = previousSubmeshes[submeshIndex];
  26597. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26598. }
  26599. this.synchronizeInstances();
  26600. return this;
  26601. };
  26602. /**
  26603. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26604. * In other words, more vertices, no more indices and a single bigger VBO.
  26605. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26606. * Returns the Mesh.
  26607. */
  26608. Mesh.prototype.convertToUnIndexedMesh = function () {
  26609. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26610. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26611. var kinds = this.getVerticesDataKinds();
  26612. var vbs = {};
  26613. var data = {};
  26614. var newdata = {};
  26615. var kindIndex;
  26616. var kind;
  26617. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26618. kind = kinds[kindIndex];
  26619. var vertexBuffer = this.getVertexBuffer(kind);
  26620. vbs[kind] = vertexBuffer;
  26621. data[kind] = vbs[kind].getData();
  26622. newdata[kind] = [];
  26623. }
  26624. // Save previous submeshes
  26625. var previousSubmeshes = this.subMeshes.slice(0);
  26626. var indices = this.getIndices();
  26627. var totalIndices = this.getTotalIndices();
  26628. // Generating unique vertices per face
  26629. var index;
  26630. for (index = 0; index < totalIndices; index++) {
  26631. var vertexIndex = indices[index];
  26632. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26633. kind = kinds[kindIndex];
  26634. var stride = vbs[kind].getStrideSize();
  26635. for (var offset = 0; offset < stride; offset++) {
  26636. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26637. }
  26638. }
  26639. }
  26640. // Updating indices
  26641. for (index = 0; index < totalIndices; index += 3) {
  26642. indices[index] = index;
  26643. indices[index + 1] = index + 1;
  26644. indices[index + 2] = index + 2;
  26645. }
  26646. this.setIndices(indices);
  26647. // Updating vertex buffers
  26648. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26649. kind = kinds[kindIndex];
  26650. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26651. }
  26652. // Updating submeshes
  26653. this.releaseSubMeshes();
  26654. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26655. var previousOne = previousSubmeshes[submeshIndex];
  26656. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26657. }
  26658. this._unIndexed = true;
  26659. this.synchronizeInstances();
  26660. return this;
  26661. };
  26662. /**
  26663. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26664. * This method returns the Mesh.
  26665. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26666. */
  26667. Mesh.prototype.flipFaces = function (flipNormals) {
  26668. if (flipNormals === void 0) { flipNormals = false; }
  26669. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26670. var i;
  26671. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26672. for (i = 0; i < vertex_data.normals.length; i++) {
  26673. vertex_data.normals[i] *= -1;
  26674. }
  26675. }
  26676. if (vertex_data.indices) {
  26677. var temp;
  26678. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26679. // reassign indices
  26680. temp = vertex_data.indices[i + 1];
  26681. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26682. vertex_data.indices[i + 2] = temp;
  26683. }
  26684. }
  26685. vertex_data.applyToMesh(this);
  26686. return this;
  26687. };
  26688. // Instances
  26689. /**
  26690. * Creates a new InstancedMesh object from the mesh model.
  26691. * An instance shares the same properties and the same material than its model.
  26692. * Only these properties of each instance can then be set individually :
  26693. * - position
  26694. * - rotation
  26695. * - rotationQuaternion
  26696. * - setPivotMatrix
  26697. * - scaling
  26698. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26699. * Warning : this method is not supported for Line mesh and LineSystem
  26700. */
  26701. Mesh.prototype.createInstance = function (name) {
  26702. return new BABYLON.InstancedMesh(name, this);
  26703. };
  26704. /**
  26705. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26706. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26707. * This method returns the Mesh.
  26708. */
  26709. Mesh.prototype.synchronizeInstances = function () {
  26710. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26711. var instance = this.instances[instanceIndex];
  26712. instance._syncSubMeshes();
  26713. }
  26714. return this;
  26715. };
  26716. /**
  26717. * Simplify the mesh according to the given array of settings.
  26718. * Function will return immediately and will simplify async. It returns the Mesh.
  26719. * @param settings a collection of simplification settings.
  26720. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26721. * @param type the type of simplification to run.
  26722. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26723. */
  26724. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26725. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26726. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26727. this.getScene().simplificationQueue.addTask({
  26728. settings: settings,
  26729. parallelProcessing: parallelProcessing,
  26730. mesh: this,
  26731. simplificationType: simplificationType,
  26732. successCallback: successCallback
  26733. });
  26734. return this;
  26735. };
  26736. /**
  26737. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26738. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26739. * This should be used together with the simplification to avoid disappearing triangles.
  26740. * Returns the Mesh.
  26741. * @param successCallback an optional success callback to be called after the optimization finished.
  26742. */
  26743. Mesh.prototype.optimizeIndices = function (successCallback) {
  26744. var _this = this;
  26745. var indices = this.getIndices();
  26746. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26747. if (!positions || !indices) {
  26748. return this;
  26749. }
  26750. var vectorPositions = new Array();
  26751. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26752. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26753. }
  26754. var dupes = new Array();
  26755. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26756. var realPos = vectorPositions.length - 1 - iteration;
  26757. var testedPosition = vectorPositions[realPos];
  26758. for (var j = 0; j < realPos; ++j) {
  26759. var againstPosition = vectorPositions[j];
  26760. if (testedPosition.equals(againstPosition)) {
  26761. dupes[realPos] = j;
  26762. break;
  26763. }
  26764. }
  26765. }, function () {
  26766. for (var i = 0; i < indices.length; ++i) {
  26767. indices[i] = dupes[indices[i]] || indices[i];
  26768. }
  26769. //indices are now reordered
  26770. var originalSubMeshes = _this.subMeshes.slice(0);
  26771. _this.setIndices(indices);
  26772. _this.subMeshes = originalSubMeshes;
  26773. if (successCallback) {
  26774. successCallback(_this);
  26775. }
  26776. });
  26777. return this;
  26778. };
  26779. Mesh.prototype.serialize = function (serializationObject) {
  26780. serializationObject.name = this.name;
  26781. serializationObject.id = this.id;
  26782. serializationObject.type = this.getClassName();
  26783. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26784. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26785. }
  26786. serializationObject.position = this.position.asArray();
  26787. if (this.rotationQuaternion) {
  26788. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26789. }
  26790. else if (this.rotation) {
  26791. serializationObject.rotation = this.rotation.asArray();
  26792. }
  26793. serializationObject.scaling = this.scaling.asArray();
  26794. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26795. serializationObject.isEnabled = this.isEnabled(false);
  26796. serializationObject.isVisible = this.isVisible;
  26797. serializationObject.infiniteDistance = this.infiniteDistance;
  26798. serializationObject.pickable = this.isPickable;
  26799. serializationObject.receiveShadows = this.receiveShadows;
  26800. serializationObject.billboardMode = this.billboardMode;
  26801. serializationObject.visibility = this.visibility;
  26802. serializationObject.checkCollisions = this.checkCollisions;
  26803. serializationObject.isBlocker = this.isBlocker;
  26804. // Parent
  26805. if (this.parent) {
  26806. serializationObject.parentId = this.parent.id;
  26807. }
  26808. // Geometry
  26809. serializationObject.isUnIndexed = this.isUnIndexed;
  26810. var geometry = this._geometry;
  26811. if (geometry) {
  26812. var geometryId = geometry.id;
  26813. serializationObject.geometryId = geometryId;
  26814. // SubMeshes
  26815. serializationObject.subMeshes = [];
  26816. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26817. var subMesh = this.subMeshes[subIndex];
  26818. serializationObject.subMeshes.push({
  26819. materialIndex: subMesh.materialIndex,
  26820. verticesStart: subMesh.verticesStart,
  26821. verticesCount: subMesh.verticesCount,
  26822. indexStart: subMesh.indexStart,
  26823. indexCount: subMesh.indexCount
  26824. });
  26825. }
  26826. }
  26827. // Material
  26828. if (this.material) {
  26829. serializationObject.materialId = this.material.id;
  26830. }
  26831. else {
  26832. this.material = null;
  26833. }
  26834. // Morph targets
  26835. if (this.morphTargetManager) {
  26836. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26837. }
  26838. // Skeleton
  26839. if (this.skeleton) {
  26840. serializationObject.skeletonId = this.skeleton.id;
  26841. }
  26842. // Physics
  26843. //TODO implement correct serialization for physics impostors.
  26844. var impostor = this.getPhysicsImpostor();
  26845. if (impostor) {
  26846. serializationObject.physicsMass = impostor.getParam("mass");
  26847. serializationObject.physicsFriction = impostor.getParam("friction");
  26848. serializationObject.physicsRestitution = impostor.getParam("mass");
  26849. serializationObject.physicsImpostor = impostor.type;
  26850. }
  26851. // Metadata
  26852. if (this.metadata) {
  26853. serializationObject.metadata = this.metadata;
  26854. }
  26855. // Instances
  26856. serializationObject.instances = [];
  26857. for (var index = 0; index < this.instances.length; index++) {
  26858. var instance = this.instances[index];
  26859. var serializationInstance = {
  26860. name: instance.name,
  26861. id: instance.id,
  26862. position: instance.position.asArray(),
  26863. scaling: instance.scaling.asArray()
  26864. };
  26865. if (instance.rotationQuaternion) {
  26866. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26867. }
  26868. else if (instance.rotation) {
  26869. serializationInstance.rotation = instance.rotation.asArray();
  26870. }
  26871. serializationObject.instances.push(serializationInstance);
  26872. // Animations
  26873. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26874. serializationInstance.ranges = instance.serializeAnimationRanges();
  26875. }
  26876. //
  26877. // Animations
  26878. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26879. serializationObject.ranges = this.serializeAnimationRanges();
  26880. // Layer mask
  26881. serializationObject.layerMask = this.layerMask;
  26882. // Alpha
  26883. serializationObject.alphaIndex = this.alphaIndex;
  26884. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26885. // Overlay
  26886. serializationObject.overlayAlpha = this.overlayAlpha;
  26887. serializationObject.overlayColor = this.overlayColor.asArray();
  26888. serializationObject.renderOverlay = this.renderOverlay;
  26889. // Fog
  26890. serializationObject.applyFog = this.applyFog;
  26891. // Action Manager
  26892. if (this.actionManager) {
  26893. serializationObject.actions = this.actionManager.serialize(this.name);
  26894. }
  26895. };
  26896. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26897. if (!this.geometry) {
  26898. return;
  26899. }
  26900. this._markSubMeshesAsAttributesDirty();
  26901. var morphTargetManager = this._morphTargetManager;
  26902. if (morphTargetManager && morphTargetManager.vertexCount) {
  26903. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26904. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26905. this.morphTargetManager = null;
  26906. return;
  26907. }
  26908. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26909. var morphTarget = morphTargetManager.getActiveTarget(index);
  26910. var positions = morphTarget.getPositions();
  26911. if (!positions) {
  26912. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26913. return;
  26914. }
  26915. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26916. var normals = morphTarget.getNormals();
  26917. if (normals) {
  26918. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26919. }
  26920. var tangents = morphTarget.getTangents();
  26921. if (tangents) {
  26922. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26923. }
  26924. }
  26925. }
  26926. else {
  26927. var index = 0;
  26928. // Positions
  26929. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26930. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26931. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26932. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26933. }
  26934. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26935. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26936. }
  26937. index++;
  26938. }
  26939. }
  26940. };
  26941. // Statics
  26942. /**
  26943. * Returns a new Mesh object parsed from the source provided.
  26944. * The parameter `parsedMesh` is the source.
  26945. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26946. */
  26947. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26948. var mesh;
  26949. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26950. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26951. }
  26952. else {
  26953. mesh = new Mesh(parsedMesh.name, scene);
  26954. }
  26955. mesh.id = parsedMesh.id;
  26956. if (BABYLON.Tags) {
  26957. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26958. }
  26959. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26960. if (parsedMesh.metadata !== undefined) {
  26961. mesh.metadata = parsedMesh.metadata;
  26962. }
  26963. if (parsedMesh.rotationQuaternion) {
  26964. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26965. }
  26966. else if (parsedMesh.rotation) {
  26967. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26968. }
  26969. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26970. if (parsedMesh.localMatrix) {
  26971. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26972. }
  26973. else if (parsedMesh.pivotMatrix) {
  26974. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26975. }
  26976. mesh.setEnabled(parsedMesh.isEnabled);
  26977. mesh.isVisible = parsedMesh.isVisible;
  26978. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26979. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26980. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26981. if (parsedMesh.applyFog !== undefined) {
  26982. mesh.applyFog = parsedMesh.applyFog;
  26983. }
  26984. if (parsedMesh.pickable !== undefined) {
  26985. mesh.isPickable = parsedMesh.pickable;
  26986. }
  26987. if (parsedMesh.alphaIndex !== undefined) {
  26988. mesh.alphaIndex = parsedMesh.alphaIndex;
  26989. }
  26990. mesh.receiveShadows = parsedMesh.receiveShadows;
  26991. mesh.billboardMode = parsedMesh.billboardMode;
  26992. if (parsedMesh.visibility !== undefined) {
  26993. mesh.visibility = parsedMesh.visibility;
  26994. }
  26995. mesh.checkCollisions = parsedMesh.checkCollisions;
  26996. if (parsedMesh.isBlocker !== undefined) {
  26997. mesh.isBlocker = parsedMesh.isBlocker;
  26998. }
  26999. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27000. // freezeWorldMatrix
  27001. if (parsedMesh.freezeWorldMatrix) {
  27002. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27003. }
  27004. // Parent
  27005. if (parsedMesh.parentId) {
  27006. mesh._waitingParentId = parsedMesh.parentId;
  27007. }
  27008. // Actions
  27009. if (parsedMesh.actions !== undefined) {
  27010. mesh._waitingActions = parsedMesh.actions;
  27011. }
  27012. // Overlay
  27013. if (parsedMesh.overlayAlpha !== undefined) {
  27014. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27015. }
  27016. if (parsedMesh.overlayColor !== undefined) {
  27017. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27018. }
  27019. if (parsedMesh.renderOverlay !== undefined) {
  27020. mesh.renderOverlay = parsedMesh.renderOverlay;
  27021. }
  27022. // Geometry
  27023. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27024. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27025. if (parsedMesh.delayLoadingFile) {
  27026. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27027. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27028. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27029. if (parsedMesh._binaryInfo) {
  27030. mesh._binaryInfo = parsedMesh._binaryInfo;
  27031. }
  27032. mesh._delayInfo = [];
  27033. if (parsedMesh.hasUVs) {
  27034. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27035. }
  27036. if (parsedMesh.hasUVs2) {
  27037. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27038. }
  27039. if (parsedMesh.hasUVs3) {
  27040. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27041. }
  27042. if (parsedMesh.hasUVs4) {
  27043. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27044. }
  27045. if (parsedMesh.hasUVs5) {
  27046. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27047. }
  27048. if (parsedMesh.hasUVs6) {
  27049. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27050. }
  27051. if (parsedMesh.hasColors) {
  27052. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27053. }
  27054. if (parsedMesh.hasMatricesIndices) {
  27055. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27056. }
  27057. if (parsedMesh.hasMatricesWeights) {
  27058. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27059. }
  27060. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27061. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27062. mesh._checkDelayState();
  27063. }
  27064. }
  27065. else {
  27066. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27067. }
  27068. // Material
  27069. if (parsedMesh.materialId) {
  27070. mesh.setMaterialByID(parsedMesh.materialId);
  27071. }
  27072. else {
  27073. mesh.material = null;
  27074. }
  27075. // Morph targets
  27076. if (parsedMesh.morphTargetManagerId > -1) {
  27077. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27078. }
  27079. // Skeleton
  27080. if (parsedMesh.skeletonId > -1) {
  27081. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27082. if (parsedMesh.numBoneInfluencers) {
  27083. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27084. }
  27085. }
  27086. // Animations
  27087. if (parsedMesh.animations) {
  27088. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27089. var parsedAnimation = parsedMesh.animations[animationIndex];
  27090. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27091. }
  27092. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27093. }
  27094. if (parsedMesh.autoAnimate) {
  27095. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27096. }
  27097. // Layer Mask
  27098. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27099. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27100. }
  27101. else {
  27102. mesh.layerMask = 0x0FFFFFFF;
  27103. }
  27104. // Physics
  27105. if (parsedMesh.physicsImpostor) {
  27106. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27107. mass: parsedMesh.physicsMass,
  27108. friction: parsedMesh.physicsFriction,
  27109. restitution: parsedMesh.physicsRestitution
  27110. }, scene);
  27111. }
  27112. // Instances
  27113. if (parsedMesh.instances) {
  27114. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27115. var parsedInstance = parsedMesh.instances[index];
  27116. var instance = mesh.createInstance(parsedInstance.name);
  27117. if (parsedInstance.id) {
  27118. instance.id = parsedInstance.id;
  27119. }
  27120. if (BABYLON.Tags) {
  27121. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27122. }
  27123. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27124. if (parsedInstance.parentId) {
  27125. instance._waitingParentId = parsedInstance.parentId;
  27126. }
  27127. if (parsedInstance.rotationQuaternion) {
  27128. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27129. }
  27130. else if (parsedInstance.rotation) {
  27131. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27132. }
  27133. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27134. instance.checkCollisions = mesh.checkCollisions;
  27135. if (parsedMesh.animations) {
  27136. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27137. parsedAnimation = parsedMesh.animations[animationIndex];
  27138. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27139. }
  27140. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27141. }
  27142. }
  27143. }
  27144. return mesh;
  27145. };
  27146. /**
  27147. * Creates a ribbon mesh.
  27148. * Please consider using the same method from the MeshBuilder class instead.
  27149. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27150. *
  27151. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27152. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27153. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27154. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27155. * 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.
  27156. * 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.
  27157. * 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
  27158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27161. */
  27162. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27163. if (closeArray === void 0) { closeArray = false; }
  27164. if (updatable === void 0) { updatable = false; }
  27165. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27166. pathArray: pathArray,
  27167. closeArray: closeArray,
  27168. closePath: closePath,
  27169. offset: offset,
  27170. updatable: updatable,
  27171. sideOrientation: sideOrientation,
  27172. instance: instance
  27173. }, scene);
  27174. };
  27175. /**
  27176. * Creates a plane polygonal mesh. By default, this is a disc.
  27177. * Please consider using the same method from the MeshBuilder class instead.
  27178. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27179. * 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.
  27180. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27183. */
  27184. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27185. if (scene === void 0) { scene = null; }
  27186. var options = {
  27187. radius: radius,
  27188. tessellation: tessellation,
  27189. sideOrientation: sideOrientation,
  27190. updatable: updatable
  27191. };
  27192. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27193. };
  27194. /**
  27195. * Creates a box mesh.
  27196. * Please consider using the same method from the MeshBuilder class instead.
  27197. * The parameter `size` sets the size (float) of each box side (default 1).
  27198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27199. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27201. */
  27202. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27203. if (scene === void 0) { scene = null; }
  27204. var options = {
  27205. size: size,
  27206. sideOrientation: sideOrientation,
  27207. updatable: updatable
  27208. };
  27209. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27210. };
  27211. /**
  27212. * Creates a sphere mesh.
  27213. * Please consider using the same method from the MeshBuilder class instead.
  27214. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27215. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27219. */
  27220. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27221. var options = {
  27222. segments: segments,
  27223. diameterX: diameter,
  27224. diameterY: diameter,
  27225. diameterZ: diameter,
  27226. sideOrientation: sideOrientation,
  27227. updatable: updatable
  27228. };
  27229. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27230. };
  27231. /**
  27232. * Creates a cylinder or a cone mesh.
  27233. * Please consider using the same method from the MeshBuilder class instead.
  27234. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27235. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27236. * 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.
  27237. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27238. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27239. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27240. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27242. */
  27243. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27244. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27245. if (scene !== undefined) {
  27246. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27247. updatable = scene;
  27248. }
  27249. scene = subdivisions;
  27250. subdivisions = 1;
  27251. }
  27252. var options = {
  27253. height: height,
  27254. diameterTop: diameterTop,
  27255. diameterBottom: diameterBottom,
  27256. tessellation: tessellation,
  27257. subdivisions: subdivisions,
  27258. sideOrientation: sideOrientation,
  27259. updatable: updatable
  27260. };
  27261. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27262. };
  27263. // Torus (Code from SharpDX.org)
  27264. /**
  27265. * Creates a torus mesh.
  27266. * Please consider using the same method from the MeshBuilder class instead.
  27267. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27268. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27269. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27270. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27273. */
  27274. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27275. var options = {
  27276. diameter: diameter,
  27277. thickness: thickness,
  27278. tessellation: tessellation,
  27279. sideOrientation: sideOrientation,
  27280. updatable: updatable
  27281. };
  27282. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27283. };
  27284. /**
  27285. * Creates a torus knot mesh.
  27286. * Please consider using the same method from the MeshBuilder class instead.
  27287. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27288. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27289. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27290. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27294. */
  27295. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27296. var options = {
  27297. radius: radius,
  27298. tube: tube,
  27299. radialSegments: radialSegments,
  27300. tubularSegments: tubularSegments,
  27301. p: p,
  27302. q: q,
  27303. sideOrientation: sideOrientation,
  27304. updatable: updatable
  27305. };
  27306. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27307. };
  27308. /**
  27309. * Creates a line mesh.
  27310. * Please consider using the same method from the MeshBuilder class instead.
  27311. * 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.
  27312. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27313. * The parameter `points` is an array successive Vector3.
  27314. * 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
  27315. * When updating an instance, remember that only point positions can change, not the number of points.
  27316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27317. */
  27318. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27319. if (scene === void 0) { scene = null; }
  27320. if (updatable === void 0) { updatable = false; }
  27321. if (instance === void 0) { instance = null; }
  27322. var options = {
  27323. points: points,
  27324. updatable: updatable,
  27325. instance: instance
  27326. };
  27327. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27328. };
  27329. /**
  27330. * Creates a dashed line mesh.
  27331. * Please consider using the same method from the MeshBuilder class instead.
  27332. * 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.
  27333. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27334. * The parameter `points` is an array successive Vector3.
  27335. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27336. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27337. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27338. * 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
  27339. * When updating an instance, remember that only point positions can change, not the number of points.
  27340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27341. */
  27342. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27343. if (scene === void 0) { scene = null; }
  27344. var options = {
  27345. points: points,
  27346. dashSize: dashSize,
  27347. gapSize: gapSize,
  27348. dashNb: dashNb,
  27349. updatable: updatable,
  27350. instance: instance
  27351. };
  27352. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27353. };
  27354. /**
  27355. * Creates a polygon mesh.
  27356. * Please consider using the same method from the MeshBuilder class instead.
  27357. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27358. * 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.
  27359. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27361. * Remember you can only change the shape positions, not their number when updating a polygon.
  27362. */
  27363. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27364. var options = {
  27365. shape: shape,
  27366. holes: holes,
  27367. updatable: updatable,
  27368. sideOrientation: sideOrientation
  27369. };
  27370. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27371. };
  27372. /**
  27373. * Creates an extruded polygon mesh, with depth in the Y direction.
  27374. * Please consider using the same method from the MeshBuilder class instead.
  27375. */
  27376. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27377. var options = {
  27378. shape: shape,
  27379. holes: holes,
  27380. depth: depth,
  27381. updatable: updatable,
  27382. sideOrientation: sideOrientation
  27383. };
  27384. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27385. };
  27386. /**
  27387. * Creates an extruded shape mesh.
  27388. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27389. * Please consider using the same method from the MeshBuilder class instead.
  27390. *
  27391. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27392. * 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
  27393. * extruded along the Z axis.
  27394. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27395. * 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.
  27396. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27397. * 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
  27398. * 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
  27399. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27403. */
  27404. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27405. if (scene === void 0) { scene = null; }
  27406. var options = {
  27407. shape: shape,
  27408. path: path,
  27409. scale: scale,
  27410. rotation: rotation,
  27411. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27412. sideOrientation: sideOrientation,
  27413. instance: instance,
  27414. updatable: updatable
  27415. };
  27416. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27417. };
  27418. /**
  27419. * Creates an custom extruded shape mesh.
  27420. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27421. * Please consider using the same method from the MeshBuilder class instead.
  27422. *
  27423. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27424. * 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
  27425. * extruded along the Z axis.
  27426. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27427. * 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
  27428. * and the distance of this point from the begining of the path :
  27429. * ```javascript
  27430. * var rotationFunction = function(i, distance) {
  27431. * // do things
  27432. * return rotationValue; }
  27433. * ```
  27434. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27435. * 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
  27436. * and the distance of this point from the begining of the path :
  27437. * ```javascript
  27438. * var scaleFunction = function(i, distance) {
  27439. * // do things
  27440. * return scaleValue;}
  27441. * ```
  27442. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27443. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27444. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27445. * 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
  27446. * 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
  27447. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27451. */
  27452. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27453. var options = {
  27454. shape: shape,
  27455. path: path,
  27456. scaleFunction: scaleFunction,
  27457. rotationFunction: rotationFunction,
  27458. ribbonCloseArray: ribbonCloseArray,
  27459. ribbonClosePath: ribbonClosePath,
  27460. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27461. sideOrientation: sideOrientation,
  27462. instance: instance,
  27463. updatable: updatable
  27464. };
  27465. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27466. };
  27467. /**
  27468. * Creates lathe mesh.
  27469. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27470. * Please consider using the same method from the MeshBuilder class instead.
  27471. * 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
  27472. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27473. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27474. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27478. */
  27479. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27480. var options = {
  27481. shape: shape,
  27482. radius: radius,
  27483. tessellation: tessellation,
  27484. sideOrientation: sideOrientation,
  27485. updatable: updatable
  27486. };
  27487. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27488. };
  27489. /**
  27490. * Creates a plane mesh.
  27491. * Please consider using the same method from the MeshBuilder class instead.
  27492. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27496. */
  27497. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27498. var options = {
  27499. size: size,
  27500. width: size,
  27501. height: size,
  27502. sideOrientation: sideOrientation,
  27503. updatable: updatable
  27504. };
  27505. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27506. };
  27507. /**
  27508. * Creates a ground mesh.
  27509. * Please consider using the same method from the MeshBuilder class instead.
  27510. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27511. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27513. */
  27514. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27515. var options = {
  27516. width: width,
  27517. height: height,
  27518. subdivisions: subdivisions,
  27519. updatable: updatable
  27520. };
  27521. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27522. };
  27523. /**
  27524. * Creates a tiled ground mesh.
  27525. * Please consider using the same method from the MeshBuilder class instead.
  27526. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27527. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27528. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27529. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27530. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27531. * numbers of subdivisions on the ground width and height of each tile.
  27532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27533. */
  27534. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27535. var options = {
  27536. xmin: xmin,
  27537. zmin: zmin,
  27538. xmax: xmax,
  27539. zmax: zmax,
  27540. subdivisions: subdivisions,
  27541. precision: precision,
  27542. updatable: updatable
  27543. };
  27544. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27545. };
  27546. /**
  27547. * Creates a ground mesh from a height map.
  27548. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27549. * Please consider using the same method from the MeshBuilder class instead.
  27550. * The parameter `url` sets the URL of the height map image resource.
  27551. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27552. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27553. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27554. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27555. * 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).
  27556. * This function is passed the newly built mesh :
  27557. * ```javascript
  27558. * function(mesh) { // do things
  27559. * return; }
  27560. * ```
  27561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27562. */
  27563. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27564. var options = {
  27565. width: width,
  27566. height: height,
  27567. subdivisions: subdivisions,
  27568. minHeight: minHeight,
  27569. maxHeight: maxHeight,
  27570. updatable: updatable,
  27571. onReady: onReady
  27572. };
  27573. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27574. };
  27575. /**
  27576. * Creates a tube mesh.
  27577. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27578. * Please consider using the same method from the MeshBuilder class instead.
  27579. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27580. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27581. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27582. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27583. * 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.
  27584. * It must return a radius value (positive float) :
  27585. * ```javascript
  27586. * var radiusFunction = function(i, distance) {
  27587. * // do things
  27588. * return radius; }
  27589. * ```
  27590. * 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
  27591. * 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
  27592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27593. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27595. */
  27596. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27597. var options = {
  27598. path: path,
  27599. radius: radius,
  27600. tessellation: tessellation,
  27601. radiusFunction: radiusFunction,
  27602. arc: 1,
  27603. cap: cap,
  27604. updatable: updatable,
  27605. sideOrientation: sideOrientation,
  27606. instance: instance
  27607. };
  27608. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27609. };
  27610. /**
  27611. * Creates a polyhedron mesh.
  27612. * Please consider using the same method from the MeshBuilder class instead.
  27613. * 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
  27614. * to choose the wanted type.
  27615. * The parameter `size` (positive float, default 1) sets the polygon size.
  27616. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27617. * 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`.
  27618. * 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
  27619. * 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)`).
  27620. * 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
  27621. * 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.
  27622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27625. */
  27626. Mesh.CreatePolyhedron = function (name, options, scene) {
  27627. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27628. };
  27629. /**
  27630. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27631. * Please consider using the same method from the MeshBuilder class instead.
  27632. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27633. * 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`).
  27634. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27635. * 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.
  27636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27639. */
  27640. Mesh.CreateIcoSphere = function (name, options, scene) {
  27641. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27642. };
  27643. /**
  27644. * Creates a decal mesh.
  27645. * Please consider using the same method from the MeshBuilder class instead.
  27646. * 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.
  27647. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27648. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27649. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27650. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27651. */
  27652. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27653. var options = {
  27654. position: position,
  27655. normal: normal,
  27656. size: size,
  27657. angle: angle
  27658. };
  27659. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27660. };
  27661. // Skeletons
  27662. /**
  27663. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27664. */
  27665. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27666. if (!this._sourcePositions) {
  27667. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27668. if (!source) {
  27669. return this._sourcePositions;
  27670. }
  27671. this._sourcePositions = new Float32Array(source);
  27672. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27673. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27674. }
  27675. }
  27676. return this._sourcePositions;
  27677. };
  27678. /**
  27679. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27680. */
  27681. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27682. if (!this._sourceNormals) {
  27683. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27684. if (!source) {
  27685. return this._sourceNormals;
  27686. }
  27687. this._sourceNormals = new Float32Array(source);
  27688. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27689. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27690. }
  27691. }
  27692. return this._sourceNormals;
  27693. };
  27694. /**
  27695. * Updates the vertex buffer by applying transformation from the bones.
  27696. * Returns the Mesh.
  27697. *
  27698. * @param {skeleton} skeleton to apply
  27699. */
  27700. Mesh.prototype.applySkeleton = function (skeleton) {
  27701. if (!this.geometry) {
  27702. return this;
  27703. }
  27704. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27705. return this;
  27706. }
  27707. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27708. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27709. return this;
  27710. }
  27711. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27712. return this;
  27713. }
  27714. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27715. return this;
  27716. }
  27717. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27718. return this;
  27719. }
  27720. if (!this._sourcePositions) {
  27721. var submeshes = this.subMeshes.slice();
  27722. this.setPositionsForCPUSkinning();
  27723. this.subMeshes = submeshes;
  27724. }
  27725. if (!this._sourceNormals) {
  27726. this.setNormalsForCPUSkinning();
  27727. }
  27728. // positionsData checks for not being Float32Array will only pass at most once
  27729. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27730. if (!positionsData) {
  27731. return this;
  27732. }
  27733. if (!(positionsData instanceof Float32Array)) {
  27734. positionsData = new Float32Array(positionsData);
  27735. }
  27736. // normalsData checks for not being Float32Array will only pass at most once
  27737. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27738. if (!normalsData) {
  27739. return this;
  27740. }
  27741. if (!(normalsData instanceof Float32Array)) {
  27742. normalsData = new Float32Array(normalsData);
  27743. }
  27744. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27745. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27746. if (!matricesWeightsData || !matricesIndicesData) {
  27747. return this;
  27748. }
  27749. var needExtras = this.numBoneInfluencers > 4;
  27750. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27751. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27752. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27753. var tempVector3 = BABYLON.Vector3.Zero();
  27754. var finalMatrix = new BABYLON.Matrix();
  27755. var tempMatrix = new BABYLON.Matrix();
  27756. var matWeightIdx = 0;
  27757. var inf;
  27758. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27759. var weight;
  27760. for (inf = 0; inf < 4; inf++) {
  27761. weight = matricesWeightsData[matWeightIdx + inf];
  27762. if (weight > 0) {
  27763. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27764. finalMatrix.addToSelf(tempMatrix);
  27765. }
  27766. else
  27767. break;
  27768. }
  27769. if (needExtras) {
  27770. for (inf = 0; inf < 4; inf++) {
  27771. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27772. if (weight > 0) {
  27773. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27774. finalMatrix.addToSelf(tempMatrix);
  27775. }
  27776. else
  27777. break;
  27778. }
  27779. }
  27780. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27781. tempVector3.toArray(positionsData, index);
  27782. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27783. tempVector3.toArray(normalsData, index);
  27784. finalMatrix.reset();
  27785. }
  27786. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27787. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27788. return this;
  27789. };
  27790. // Tools
  27791. /**
  27792. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27793. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27794. */
  27795. Mesh.MinMax = function (meshes) {
  27796. var minVector = null;
  27797. var maxVector = null;
  27798. meshes.forEach(function (mesh, index, array) {
  27799. var boundingInfo = mesh.getBoundingInfo();
  27800. var boundingBox = boundingInfo.boundingBox;
  27801. if (!minVector || !maxVector) {
  27802. minVector = boundingBox.minimumWorld;
  27803. maxVector = boundingBox.maximumWorld;
  27804. }
  27805. else {
  27806. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27807. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27808. }
  27809. });
  27810. if (!minVector || !maxVector) {
  27811. return {
  27812. min: BABYLON.Vector3.Zero(),
  27813. max: BABYLON.Vector3.Zero()
  27814. };
  27815. }
  27816. return {
  27817. min: minVector,
  27818. max: maxVector
  27819. };
  27820. };
  27821. /**
  27822. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27823. */
  27824. Mesh.Center = function (meshesOrMinMaxVector) {
  27825. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27826. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27827. };
  27828. /**
  27829. * Merge the array of meshes into a single mesh for performance reasons.
  27830. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27831. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27832. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27833. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27834. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27835. */
  27836. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27837. if (disposeSource === void 0) { disposeSource = true; }
  27838. var index;
  27839. if (!allow32BitsIndices) {
  27840. var totalVertices = 0;
  27841. // Counting vertices
  27842. for (index = 0; index < meshes.length; index++) {
  27843. if (meshes[index]) {
  27844. totalVertices += meshes[index].getTotalVertices();
  27845. if (totalVertices > 65536) {
  27846. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27847. return null;
  27848. }
  27849. }
  27850. }
  27851. }
  27852. // Merge
  27853. var vertexData = null;
  27854. var otherVertexData;
  27855. var indiceArray = new Array();
  27856. var source = null;
  27857. for (index = 0; index < meshes.length; index++) {
  27858. if (meshes[index]) {
  27859. meshes[index].computeWorldMatrix(true);
  27860. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27861. otherVertexData.transform(meshes[index].getWorldMatrix());
  27862. if (vertexData) {
  27863. vertexData.merge(otherVertexData);
  27864. }
  27865. else {
  27866. vertexData = otherVertexData;
  27867. source = meshes[index];
  27868. }
  27869. if (subdivideWithSubMeshes) {
  27870. indiceArray.push(meshes[index].getTotalIndices());
  27871. }
  27872. }
  27873. }
  27874. source = source;
  27875. if (!meshSubclass) {
  27876. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27877. }
  27878. vertexData.applyToMesh(meshSubclass);
  27879. // Setting properties
  27880. meshSubclass.material = source.material;
  27881. meshSubclass.checkCollisions = source.checkCollisions;
  27882. // Cleaning
  27883. if (disposeSource) {
  27884. for (index = 0; index < meshes.length; index++) {
  27885. if (meshes[index]) {
  27886. meshes[index].dispose();
  27887. }
  27888. }
  27889. }
  27890. // Subdivide
  27891. if (subdivideWithSubMeshes) {
  27892. //-- Suppresions du submesh global
  27893. meshSubclass.releaseSubMeshes();
  27894. index = 0;
  27895. var offset = 0;
  27896. //-- aplique la subdivision en fonction du tableau d'indices
  27897. while (index < indiceArray.length) {
  27898. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27899. offset += indiceArray[index];
  27900. index++;
  27901. }
  27902. }
  27903. return meshSubclass;
  27904. };
  27905. // Consts
  27906. Mesh._FRONTSIDE = 0;
  27907. Mesh._BACKSIDE = 1;
  27908. Mesh._DOUBLESIDE = 2;
  27909. Mesh._DEFAULTSIDE = 0;
  27910. Mesh._NO_CAP = 0;
  27911. Mesh._CAP_START = 1;
  27912. Mesh._CAP_END = 2;
  27913. Mesh._CAP_ALL = 3;
  27914. return Mesh;
  27915. }(BABYLON.AbstractMesh));
  27916. BABYLON.Mesh = Mesh;
  27917. })(BABYLON || (BABYLON = {}));
  27918. //# sourceMappingURL=babylon.mesh.js.map
  27919. var BABYLON;
  27920. (function (BABYLON) {
  27921. var BaseSubMesh = /** @class */ (function () {
  27922. function BaseSubMesh() {
  27923. }
  27924. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27925. get: function () {
  27926. return this._materialEffect;
  27927. },
  27928. enumerable: true,
  27929. configurable: true
  27930. });
  27931. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27932. if (defines === void 0) { defines = null; }
  27933. if (this._materialEffect === effect) {
  27934. if (!effect) {
  27935. this._materialDefines = null;
  27936. }
  27937. return;
  27938. }
  27939. this._materialDefines = defines;
  27940. this._materialEffect = effect;
  27941. };
  27942. return BaseSubMesh;
  27943. }());
  27944. BABYLON.BaseSubMesh = BaseSubMesh;
  27945. var SubMesh = /** @class */ (function (_super) {
  27946. __extends(SubMesh, _super);
  27947. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27948. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27949. var _this = _super.call(this) || this;
  27950. _this.materialIndex = materialIndex;
  27951. _this.verticesStart = verticesStart;
  27952. _this.verticesCount = verticesCount;
  27953. _this.indexStart = indexStart;
  27954. _this.indexCount = indexCount;
  27955. _this._renderId = 0;
  27956. _this._mesh = mesh;
  27957. _this._renderingMesh = renderingMesh || mesh;
  27958. mesh.subMeshes.push(_this);
  27959. _this._trianglePlanes = [];
  27960. _this._id = mesh.subMeshes.length - 1;
  27961. if (createBoundingBox) {
  27962. _this.refreshBoundingInfo();
  27963. mesh.computeWorldMatrix(true);
  27964. }
  27965. return _this;
  27966. }
  27967. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27968. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27969. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27970. };
  27971. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27972. get: function () {
  27973. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27974. },
  27975. enumerable: true,
  27976. configurable: true
  27977. });
  27978. /**
  27979. * Returns the submesh BoudingInfo object.
  27980. */
  27981. SubMesh.prototype.getBoundingInfo = function () {
  27982. if (this.IsGlobal) {
  27983. return this._mesh.getBoundingInfo();
  27984. }
  27985. return this._boundingInfo;
  27986. };
  27987. /**
  27988. * Sets the submesh BoundingInfo.
  27989. * Return the SubMesh.
  27990. */
  27991. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27992. this._boundingInfo = boundingInfo;
  27993. return this;
  27994. };
  27995. /**
  27996. * Returns the mesh of the current submesh.
  27997. */
  27998. SubMesh.prototype.getMesh = function () {
  27999. return this._mesh;
  28000. };
  28001. /**
  28002. * Returns the rendering mesh of the submesh.
  28003. */
  28004. SubMesh.prototype.getRenderingMesh = function () {
  28005. return this._renderingMesh;
  28006. };
  28007. /**
  28008. * Returns the submesh material.
  28009. */
  28010. SubMesh.prototype.getMaterial = function () {
  28011. var rootMaterial = this._renderingMesh.material;
  28012. if (rootMaterial === null || rootMaterial === undefined) {
  28013. return this._mesh.getScene().defaultMaterial;
  28014. }
  28015. else if (rootMaterial.getSubMaterial) {
  28016. var multiMaterial = rootMaterial;
  28017. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28018. if (this._currentMaterial !== effectiveMaterial) {
  28019. this._currentMaterial = effectiveMaterial;
  28020. this._materialDefines = null;
  28021. }
  28022. return effectiveMaterial;
  28023. }
  28024. return rootMaterial;
  28025. };
  28026. // Methods
  28027. /**
  28028. * Sets a new updated BoundingInfo object to the submesh.
  28029. * Returns the SubMesh.
  28030. */
  28031. SubMesh.prototype.refreshBoundingInfo = function () {
  28032. this._lastColliderWorldVertices = null;
  28033. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28034. return this;
  28035. }
  28036. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28037. if (!data) {
  28038. this._boundingInfo = this._mesh.getBoundingInfo();
  28039. return this;
  28040. }
  28041. var indices = this._renderingMesh.getIndices();
  28042. var extend;
  28043. //is this the only submesh?
  28044. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28045. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28046. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28047. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28048. }
  28049. else {
  28050. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28051. }
  28052. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28053. return this;
  28054. };
  28055. SubMesh.prototype._checkCollision = function (collider) {
  28056. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28057. return boundingInfo._checkCollision(collider);
  28058. };
  28059. /**
  28060. * Updates the submesh BoundingInfo.
  28061. * Returns the Submesh.
  28062. */
  28063. SubMesh.prototype.updateBoundingInfo = function (world) {
  28064. var boundingInfo = this.getBoundingInfo();
  28065. if (!boundingInfo) {
  28066. this.refreshBoundingInfo();
  28067. boundingInfo = this.getBoundingInfo();
  28068. }
  28069. boundingInfo.update(world);
  28070. return this;
  28071. };
  28072. /**
  28073. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28074. * Boolean returned.
  28075. */
  28076. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28077. var boundingInfo = this.getBoundingInfo();
  28078. if (!boundingInfo) {
  28079. return false;
  28080. }
  28081. return boundingInfo.isInFrustum(frustumPlanes);
  28082. };
  28083. /**
  28084. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28085. * Boolean returned.
  28086. */
  28087. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28088. var boundingInfo = this.getBoundingInfo();
  28089. if (!boundingInfo) {
  28090. return false;
  28091. }
  28092. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28093. };
  28094. /**
  28095. * Renders the submesh.
  28096. * Returns it.
  28097. */
  28098. SubMesh.prototype.render = function (enableAlphaMode) {
  28099. this._renderingMesh.render(this, enableAlphaMode);
  28100. return this;
  28101. };
  28102. /**
  28103. * Returns a new Index Buffer.
  28104. * Type returned : WebGLBuffer.
  28105. */
  28106. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28107. if (!this._linesIndexBuffer) {
  28108. var linesIndices = [];
  28109. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28110. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28111. }
  28112. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28113. this.linesIndexCount = linesIndices.length;
  28114. }
  28115. return this._linesIndexBuffer;
  28116. };
  28117. /**
  28118. * True is the passed Ray intersects the submesh bounding box.
  28119. * Boolean returned.
  28120. */
  28121. SubMesh.prototype.canIntersects = function (ray) {
  28122. var boundingInfo = this.getBoundingInfo();
  28123. if (!boundingInfo) {
  28124. return false;
  28125. }
  28126. return ray.intersectsBox(boundingInfo.boundingBox);
  28127. };
  28128. /**
  28129. * Returns an object IntersectionInfo.
  28130. */
  28131. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28132. var intersectInfo = null;
  28133. // LineMesh first as it's also a Mesh...
  28134. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28135. var lineMesh = this._mesh;
  28136. // Line test
  28137. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28138. var p0 = positions[indices[index]];
  28139. var p1 = positions[indices[index + 1]];
  28140. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28141. if (length < 0) {
  28142. continue;
  28143. }
  28144. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28145. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28146. if (fastCheck) {
  28147. break;
  28148. }
  28149. }
  28150. }
  28151. }
  28152. else {
  28153. // Triangles test
  28154. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28155. var p0 = positions[indices[index]];
  28156. var p1 = positions[indices[index + 1]];
  28157. var p2 = positions[indices[index + 2]];
  28158. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28159. if (currentIntersectInfo) {
  28160. if (currentIntersectInfo.distance < 0) {
  28161. continue;
  28162. }
  28163. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28164. intersectInfo = currentIntersectInfo;
  28165. intersectInfo.faceId = index / 3;
  28166. if (fastCheck) {
  28167. break;
  28168. }
  28169. }
  28170. }
  28171. }
  28172. }
  28173. return intersectInfo;
  28174. };
  28175. SubMesh.prototype._rebuild = function () {
  28176. if (this._linesIndexBuffer) {
  28177. this._linesIndexBuffer = null;
  28178. }
  28179. };
  28180. // Clone
  28181. /**
  28182. * Creates a new Submesh from the passed Mesh.
  28183. */
  28184. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28185. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28186. if (!this.IsGlobal) {
  28187. var boundingInfo = this.getBoundingInfo();
  28188. if (!boundingInfo) {
  28189. return result;
  28190. }
  28191. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28192. }
  28193. return result;
  28194. };
  28195. // Dispose
  28196. /**
  28197. * Disposes the Submesh.
  28198. * Returns nothing.
  28199. */
  28200. SubMesh.prototype.dispose = function () {
  28201. if (this._linesIndexBuffer) {
  28202. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28203. this._linesIndexBuffer = null;
  28204. }
  28205. // Remove from mesh
  28206. var index = this._mesh.subMeshes.indexOf(this);
  28207. this._mesh.subMeshes.splice(index, 1);
  28208. };
  28209. // Statics
  28210. /**
  28211. * Creates a new Submesh from the passed parameters :
  28212. * - materialIndex (integer) : the index of the main mesh material.
  28213. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28214. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28215. * - mesh (Mesh) : the main mesh to create the submesh from.
  28216. * - renderingMesh (optional Mesh) : rendering mesh.
  28217. */
  28218. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28219. var minVertexIndex = Number.MAX_VALUE;
  28220. var maxVertexIndex = -Number.MAX_VALUE;
  28221. renderingMesh = (renderingMesh || mesh);
  28222. var indices = renderingMesh.getIndices();
  28223. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28224. var vertexIndex = indices[index];
  28225. if (vertexIndex < minVertexIndex)
  28226. minVertexIndex = vertexIndex;
  28227. if (vertexIndex > maxVertexIndex)
  28228. maxVertexIndex = vertexIndex;
  28229. }
  28230. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28231. };
  28232. return SubMesh;
  28233. }(BaseSubMesh));
  28234. BABYLON.SubMesh = SubMesh;
  28235. })(BABYLON || (BABYLON = {}));
  28236. //# sourceMappingURL=babylon.subMesh.js.map
  28237. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28238. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28239. s = arguments[i];
  28240. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28241. t[p] = s[p];
  28242. }
  28243. return t;
  28244. };
  28245. var BABYLON;
  28246. (function (BABYLON) {
  28247. var MaterialDefines = /** @class */ (function () {
  28248. function MaterialDefines() {
  28249. this._isDirty = true;
  28250. this._areLightsDirty = true;
  28251. this._areAttributesDirty = true;
  28252. this._areTexturesDirty = true;
  28253. this._areFresnelDirty = true;
  28254. this._areMiscDirty = true;
  28255. this._areImageProcessingDirty = true;
  28256. this._normals = false;
  28257. this._uvs = false;
  28258. this._needNormals = false;
  28259. this._needUVs = false;
  28260. }
  28261. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28262. get: function () {
  28263. return this._isDirty;
  28264. },
  28265. enumerable: true,
  28266. configurable: true
  28267. });
  28268. MaterialDefines.prototype.markAsProcessed = function () {
  28269. this._isDirty = false;
  28270. this._areAttributesDirty = false;
  28271. this._areTexturesDirty = false;
  28272. this._areFresnelDirty = false;
  28273. this._areLightsDirty = false;
  28274. this._areMiscDirty = false;
  28275. this._areImageProcessingDirty = false;
  28276. };
  28277. MaterialDefines.prototype.markAsUnprocessed = function () {
  28278. this._isDirty = true;
  28279. };
  28280. MaterialDefines.prototype.markAllAsDirty = function () {
  28281. this._areTexturesDirty = true;
  28282. this._areAttributesDirty = true;
  28283. this._areLightsDirty = true;
  28284. this._areFresnelDirty = true;
  28285. this._areMiscDirty = true;
  28286. this._areImageProcessingDirty = true;
  28287. this._isDirty = true;
  28288. };
  28289. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28290. this._areImageProcessingDirty = true;
  28291. this._isDirty = true;
  28292. };
  28293. MaterialDefines.prototype.markAsLightDirty = function () {
  28294. this._areLightsDirty = true;
  28295. this._isDirty = true;
  28296. };
  28297. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28298. this._areAttributesDirty = true;
  28299. this._isDirty = true;
  28300. };
  28301. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28302. this._areTexturesDirty = true;
  28303. this._isDirty = true;
  28304. };
  28305. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28306. this._areFresnelDirty = true;
  28307. this._isDirty = true;
  28308. };
  28309. MaterialDefines.prototype.markAsMiscDirty = function () {
  28310. this._areMiscDirty = true;
  28311. this._isDirty = true;
  28312. };
  28313. MaterialDefines.prototype.rebuild = function () {
  28314. if (this._keys) {
  28315. delete this._keys;
  28316. }
  28317. this._keys = [];
  28318. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28319. var key = _a[_i];
  28320. if (key[0] === "_") {
  28321. continue;
  28322. }
  28323. this._keys.push(key);
  28324. }
  28325. };
  28326. MaterialDefines.prototype.isEqual = function (other) {
  28327. if (this._keys.length !== other._keys.length) {
  28328. return false;
  28329. }
  28330. for (var index = 0; index < this._keys.length; index++) {
  28331. var prop = this._keys[index];
  28332. if (this[prop] !== other[prop]) {
  28333. return false;
  28334. }
  28335. }
  28336. return true;
  28337. };
  28338. MaterialDefines.prototype.cloneTo = function (other) {
  28339. if (this._keys.length !== other._keys.length) {
  28340. other._keys = this._keys.slice(0);
  28341. }
  28342. for (var index = 0; index < this._keys.length; index++) {
  28343. var prop = this._keys[index];
  28344. other[prop] = this[prop];
  28345. }
  28346. };
  28347. MaterialDefines.prototype.reset = function () {
  28348. for (var index = 0; index < this._keys.length; index++) {
  28349. var prop = this._keys[index];
  28350. if (typeof (this[prop]) === "number") {
  28351. this[prop] = 0;
  28352. }
  28353. else {
  28354. this[prop] = false;
  28355. }
  28356. }
  28357. };
  28358. MaterialDefines.prototype.toString = function () {
  28359. var result = "";
  28360. for (var index = 0; index < this._keys.length; index++) {
  28361. var prop = this._keys[index];
  28362. var value = this[prop];
  28363. if (typeof (value) === "number") {
  28364. result += "#define " + prop + " " + this[prop] + "\n";
  28365. }
  28366. else if (value) {
  28367. result += "#define " + prop + "\n";
  28368. }
  28369. }
  28370. return result;
  28371. };
  28372. return MaterialDefines;
  28373. }());
  28374. BABYLON.MaterialDefines = MaterialDefines;
  28375. var Material = /** @class */ (function () {
  28376. function Material(name, scene, doNotAdd) {
  28377. this.checkReadyOnEveryCall = false;
  28378. this.checkReadyOnlyOnce = false;
  28379. this.state = "";
  28380. this.alpha = 1.0;
  28381. this._backFaceCulling = true;
  28382. this.doNotSerialize = false;
  28383. this.storeEffectOnSubMeshes = false;
  28384. /**
  28385. * An event triggered when the material is disposed.
  28386. * @type {BABYLON.Observable}
  28387. */
  28388. this.onDisposeObservable = new BABYLON.Observable();
  28389. /**
  28390. * An event triggered when the material is bound.
  28391. * @type {BABYLON.Observable}
  28392. */
  28393. this.onBindObservable = new BABYLON.Observable();
  28394. /**
  28395. * An event triggered when the material is unbound.
  28396. * @type {BABYLON.Observable}
  28397. */
  28398. this.onUnBindObservable = new BABYLON.Observable();
  28399. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28400. this._needDepthPrePass = false;
  28401. this.disableDepthWrite = false;
  28402. this.forceDepthWrite = false;
  28403. this.separateCullingPass = false;
  28404. this._fogEnabled = true;
  28405. this.pointSize = 1.0;
  28406. this.zOffset = 0;
  28407. this._wasPreviouslyReady = false;
  28408. this._fillMode = Material.TriangleFillMode;
  28409. this.name = name;
  28410. this.id = name || BABYLON.Tools.RandomId();
  28411. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28412. if (this._scene.useRightHandedSystem) {
  28413. this.sideOrientation = Material.ClockWiseSideOrientation;
  28414. }
  28415. else {
  28416. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28417. }
  28418. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28419. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28420. if (!doNotAdd) {
  28421. this._scene.materials.push(this);
  28422. }
  28423. }
  28424. Object.defineProperty(Material, "TriangleFillMode", {
  28425. get: function () {
  28426. return Material._TriangleFillMode;
  28427. },
  28428. enumerable: true,
  28429. configurable: true
  28430. });
  28431. Object.defineProperty(Material, "WireFrameFillMode", {
  28432. get: function () {
  28433. return Material._WireFrameFillMode;
  28434. },
  28435. enumerable: true,
  28436. configurable: true
  28437. });
  28438. Object.defineProperty(Material, "PointFillMode", {
  28439. get: function () {
  28440. return Material._PointFillMode;
  28441. },
  28442. enumerable: true,
  28443. configurable: true
  28444. });
  28445. Object.defineProperty(Material, "PointListDrawMode", {
  28446. get: function () {
  28447. return Material._PointListDrawMode;
  28448. },
  28449. enumerable: true,
  28450. configurable: true
  28451. });
  28452. Object.defineProperty(Material, "LineListDrawMode", {
  28453. get: function () {
  28454. return Material._LineListDrawMode;
  28455. },
  28456. enumerable: true,
  28457. configurable: true
  28458. });
  28459. Object.defineProperty(Material, "LineLoopDrawMode", {
  28460. get: function () {
  28461. return Material._LineLoopDrawMode;
  28462. },
  28463. enumerable: true,
  28464. configurable: true
  28465. });
  28466. Object.defineProperty(Material, "LineStripDrawMode", {
  28467. get: function () {
  28468. return Material._LineStripDrawMode;
  28469. },
  28470. enumerable: true,
  28471. configurable: true
  28472. });
  28473. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28474. get: function () {
  28475. return Material._TriangleStripDrawMode;
  28476. },
  28477. enumerable: true,
  28478. configurable: true
  28479. });
  28480. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28481. get: function () {
  28482. return Material._TriangleFanDrawMode;
  28483. },
  28484. enumerable: true,
  28485. configurable: true
  28486. });
  28487. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28488. get: function () {
  28489. return Material._ClockWiseSideOrientation;
  28490. },
  28491. enumerable: true,
  28492. configurable: true
  28493. });
  28494. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28495. get: function () {
  28496. return Material._CounterClockWiseSideOrientation;
  28497. },
  28498. enumerable: true,
  28499. configurable: true
  28500. });
  28501. Object.defineProperty(Material, "TextureDirtyFlag", {
  28502. get: function () {
  28503. return Material._TextureDirtyFlag;
  28504. },
  28505. enumerable: true,
  28506. configurable: true
  28507. });
  28508. Object.defineProperty(Material, "LightDirtyFlag", {
  28509. get: function () {
  28510. return Material._LightDirtyFlag;
  28511. },
  28512. enumerable: true,
  28513. configurable: true
  28514. });
  28515. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28516. get: function () {
  28517. return Material._FresnelDirtyFlag;
  28518. },
  28519. enumerable: true,
  28520. configurable: true
  28521. });
  28522. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28523. get: function () {
  28524. return Material._AttributesDirtyFlag;
  28525. },
  28526. enumerable: true,
  28527. configurable: true
  28528. });
  28529. Object.defineProperty(Material, "MiscDirtyFlag", {
  28530. get: function () {
  28531. return Material._MiscDirtyFlag;
  28532. },
  28533. enumerable: true,
  28534. configurable: true
  28535. });
  28536. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28537. get: function () {
  28538. return this._backFaceCulling;
  28539. },
  28540. set: function (value) {
  28541. if (this._backFaceCulling === value) {
  28542. return;
  28543. }
  28544. this._backFaceCulling = value;
  28545. this.markAsDirty(Material.TextureDirtyFlag);
  28546. },
  28547. enumerable: true,
  28548. configurable: true
  28549. });
  28550. Object.defineProperty(Material.prototype, "onDispose", {
  28551. set: function (callback) {
  28552. if (this._onDisposeObserver) {
  28553. this.onDisposeObservable.remove(this._onDisposeObserver);
  28554. }
  28555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28556. },
  28557. enumerable: true,
  28558. configurable: true
  28559. });
  28560. Object.defineProperty(Material.prototype, "onBind", {
  28561. set: function (callback) {
  28562. if (this._onBindObserver) {
  28563. this.onBindObservable.remove(this._onBindObserver);
  28564. }
  28565. this._onBindObserver = this.onBindObservable.add(callback);
  28566. },
  28567. enumerable: true,
  28568. configurable: true
  28569. });
  28570. Object.defineProperty(Material.prototype, "alphaMode", {
  28571. get: function () {
  28572. return this._alphaMode;
  28573. },
  28574. set: function (value) {
  28575. if (this._alphaMode === value) {
  28576. return;
  28577. }
  28578. this._alphaMode = value;
  28579. this.markAsDirty(Material.TextureDirtyFlag);
  28580. },
  28581. enumerable: true,
  28582. configurable: true
  28583. });
  28584. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28585. get: function () {
  28586. return this._needDepthPrePass;
  28587. },
  28588. set: function (value) {
  28589. if (this._needDepthPrePass === value) {
  28590. return;
  28591. }
  28592. this._needDepthPrePass = value;
  28593. if (this._needDepthPrePass) {
  28594. this.checkReadyOnEveryCall = true;
  28595. }
  28596. },
  28597. enumerable: true,
  28598. configurable: true
  28599. });
  28600. Object.defineProperty(Material.prototype, "fogEnabled", {
  28601. get: function () {
  28602. return this._fogEnabled;
  28603. },
  28604. set: function (value) {
  28605. if (this._fogEnabled === value) {
  28606. return;
  28607. }
  28608. this._fogEnabled = value;
  28609. this.markAsDirty(Material.MiscDirtyFlag);
  28610. },
  28611. enumerable: true,
  28612. configurable: true
  28613. });
  28614. Object.defineProperty(Material.prototype, "wireframe", {
  28615. get: function () {
  28616. return this._fillMode === Material.WireFrameFillMode;
  28617. },
  28618. set: function (value) {
  28619. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28620. },
  28621. enumerable: true,
  28622. configurable: true
  28623. });
  28624. Object.defineProperty(Material.prototype, "pointsCloud", {
  28625. get: function () {
  28626. return this._fillMode === Material.PointFillMode;
  28627. },
  28628. set: function (value) {
  28629. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28630. },
  28631. enumerable: true,
  28632. configurable: true
  28633. });
  28634. Object.defineProperty(Material.prototype, "fillMode", {
  28635. get: function () {
  28636. return this._fillMode;
  28637. },
  28638. set: function (value) {
  28639. if (this._fillMode === value) {
  28640. return;
  28641. }
  28642. this._fillMode = value;
  28643. this.markAsDirty(Material.MiscDirtyFlag);
  28644. },
  28645. enumerable: true,
  28646. configurable: true
  28647. });
  28648. /**
  28649. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28650. * subclasses should override adding information pertainent to themselves
  28651. */
  28652. Material.prototype.toString = function (fullDetails) {
  28653. var ret = "Name: " + this.name;
  28654. if (fullDetails) {
  28655. }
  28656. return ret;
  28657. };
  28658. /**
  28659. * Child classes can use it to update shaders
  28660. */
  28661. Material.prototype.getClassName = function () {
  28662. return "Material";
  28663. };
  28664. Object.defineProperty(Material.prototype, "isFrozen", {
  28665. get: function () {
  28666. return this.checkReadyOnlyOnce;
  28667. },
  28668. enumerable: true,
  28669. configurable: true
  28670. });
  28671. Material.prototype.freeze = function () {
  28672. this.checkReadyOnlyOnce = true;
  28673. };
  28674. Material.prototype.unfreeze = function () {
  28675. this.checkReadyOnlyOnce = false;
  28676. };
  28677. Material.prototype.isReady = function (mesh, useInstances) {
  28678. return true;
  28679. };
  28680. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28681. return false;
  28682. };
  28683. Material.prototype.getEffect = function () {
  28684. return this._effect;
  28685. };
  28686. Material.prototype.getScene = function () {
  28687. return this._scene;
  28688. };
  28689. Material.prototype.needAlphaBlending = function () {
  28690. return (this.alpha < 1.0);
  28691. };
  28692. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28693. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28694. };
  28695. Material.prototype.needAlphaTesting = function () {
  28696. return false;
  28697. };
  28698. Material.prototype.getAlphaTestTexture = function () {
  28699. return null;
  28700. };
  28701. Material.prototype.markDirty = function () {
  28702. this._wasPreviouslyReady = false;
  28703. };
  28704. Material.prototype._preBind = function (effect, overrideOrientation) {
  28705. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28706. var engine = this._scene.getEngine();
  28707. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28708. var reverse = orientation === Material.ClockWiseSideOrientation;
  28709. engine.enableEffect(effect ? effect : this._effect);
  28710. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28711. return reverse;
  28712. };
  28713. Material.prototype.bind = function (world, mesh) {
  28714. };
  28715. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28716. };
  28717. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28718. };
  28719. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28720. sceneUbo.bindToEffect(effect, "Scene");
  28721. };
  28722. Material.prototype.bindView = function (effect) {
  28723. if (!this._useUBO) {
  28724. effect.setMatrix("view", this.getScene().getViewMatrix());
  28725. }
  28726. else {
  28727. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28728. }
  28729. };
  28730. Material.prototype.bindViewProjection = function (effect) {
  28731. if (!this._useUBO) {
  28732. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28733. }
  28734. else {
  28735. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28736. }
  28737. };
  28738. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  28739. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  28740. };
  28741. Material.prototype._afterBind = function (mesh) {
  28742. this._scene._cachedMaterial = this;
  28743. if (mesh) {
  28744. this._scene._cachedVisibility = mesh.visibility;
  28745. }
  28746. else {
  28747. this._scene._cachedVisibility = 1;
  28748. }
  28749. if (mesh) {
  28750. this.onBindObservable.notifyObservers(mesh);
  28751. }
  28752. if (this.disableDepthWrite) {
  28753. var engine = this._scene.getEngine();
  28754. this._cachedDepthWriteState = engine.getDepthWrite();
  28755. engine.setDepthWrite(false);
  28756. }
  28757. };
  28758. Material.prototype.unbind = function () {
  28759. this.onUnBindObservable.notifyObservers(this);
  28760. if (this.disableDepthWrite) {
  28761. var engine = this._scene.getEngine();
  28762. engine.setDepthWrite(this._cachedDepthWriteState);
  28763. }
  28764. };
  28765. Material.prototype.getActiveTextures = function () {
  28766. return [];
  28767. };
  28768. Material.prototype.hasTexture = function (texture) {
  28769. return false;
  28770. };
  28771. Material.prototype.clone = function (name) {
  28772. return null;
  28773. };
  28774. Material.prototype.getBindedMeshes = function () {
  28775. var result = new Array();
  28776. for (var index = 0; index < this._scene.meshes.length; index++) {
  28777. var mesh = this._scene.meshes[index];
  28778. if (mesh.material === this) {
  28779. result.push(mesh);
  28780. }
  28781. }
  28782. return result;
  28783. };
  28784. /**
  28785. * Force shader compilation including textures ready check
  28786. */
  28787. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28788. var _this = this;
  28789. var localOptions = __assign({ clipPlane: false }, options);
  28790. var subMesh = new BABYLON.BaseSubMesh();
  28791. var scene = this.getScene();
  28792. var checkReady = function () {
  28793. if (!_this._scene || !_this._scene.getEngine()) {
  28794. return;
  28795. }
  28796. if (subMesh._materialDefines) {
  28797. subMesh._materialDefines._renderId = -1;
  28798. }
  28799. var clipPlaneState = scene.clipPlane;
  28800. if (localOptions.clipPlane) {
  28801. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28802. }
  28803. if (_this.storeEffectOnSubMeshes) {
  28804. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28805. if (onCompiled) {
  28806. onCompiled(_this);
  28807. }
  28808. }
  28809. else {
  28810. setTimeout(checkReady, 16);
  28811. }
  28812. }
  28813. else {
  28814. if (_this.isReady(mesh)) {
  28815. if (onCompiled) {
  28816. onCompiled(_this);
  28817. }
  28818. }
  28819. else {
  28820. setTimeout(checkReady, 16);
  28821. }
  28822. }
  28823. if (options && options.clipPlane) {
  28824. scene.clipPlane = clipPlaneState;
  28825. }
  28826. };
  28827. checkReady();
  28828. };
  28829. Material.prototype.markAsDirty = function (flag) {
  28830. if (flag & Material.TextureDirtyFlag) {
  28831. this._markAllSubMeshesAsTexturesDirty();
  28832. }
  28833. if (flag & Material.LightDirtyFlag) {
  28834. this._markAllSubMeshesAsLightsDirty();
  28835. }
  28836. if (flag & Material.FresnelDirtyFlag) {
  28837. this._markAllSubMeshesAsFresnelDirty();
  28838. }
  28839. if (flag & Material.AttributesDirtyFlag) {
  28840. this._markAllSubMeshesAsAttributesDirty();
  28841. }
  28842. if (flag & Material.MiscDirtyFlag) {
  28843. this._markAllSubMeshesAsMiscDirty();
  28844. }
  28845. this.getScene().resetCachedMaterial();
  28846. };
  28847. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28848. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28849. var mesh = _a[_i];
  28850. if (!mesh.subMeshes) {
  28851. continue;
  28852. }
  28853. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28854. var subMesh = _c[_b];
  28855. if (subMesh.getMaterial() !== this) {
  28856. continue;
  28857. }
  28858. if (!subMesh._materialDefines) {
  28859. continue;
  28860. }
  28861. func(subMesh._materialDefines);
  28862. }
  28863. }
  28864. };
  28865. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28866. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28867. };
  28868. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28869. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28870. };
  28871. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28872. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28873. };
  28874. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28875. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28876. };
  28877. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28878. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28879. };
  28880. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28881. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28882. };
  28883. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28884. // Animations
  28885. this.getScene().stopAnimation(this);
  28886. // Remove from scene
  28887. var index = this._scene.materials.indexOf(this);
  28888. if (index >= 0) {
  28889. this._scene.materials.splice(index, 1);
  28890. }
  28891. // Remove from meshes
  28892. for (index = 0; index < this._scene.meshes.length; index++) {
  28893. var mesh = this._scene.meshes[index];
  28894. if (mesh.material === this) {
  28895. mesh.material = null;
  28896. if (mesh.geometry) {
  28897. var geometry = (mesh.geometry);
  28898. if (this.storeEffectOnSubMeshes) {
  28899. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28900. var subMesh = _a[_i];
  28901. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28902. if (forceDisposeEffect && subMesh._materialEffect) {
  28903. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28904. }
  28905. }
  28906. }
  28907. else {
  28908. geometry._releaseVertexArrayObject(this._effect);
  28909. }
  28910. }
  28911. }
  28912. }
  28913. this._uniformBuffer.dispose();
  28914. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28915. if (forceDisposeEffect && this._effect) {
  28916. if (!this.storeEffectOnSubMeshes) {
  28917. this._scene.getEngine()._releaseEffect(this._effect);
  28918. }
  28919. this._effect = null;
  28920. }
  28921. // Callback
  28922. this.onDisposeObservable.notifyObservers(this);
  28923. this.onDisposeObservable.clear();
  28924. this.onBindObservable.clear();
  28925. this.onUnBindObservable.clear();
  28926. };
  28927. Material.prototype.serialize = function () {
  28928. return BABYLON.SerializationHelper.Serialize(this);
  28929. };
  28930. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28931. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28932. multiMaterial.id = parsedMultiMaterial.id;
  28933. if (BABYLON.Tags) {
  28934. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28935. }
  28936. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28937. var subMatId = parsedMultiMaterial.materials[matIndex];
  28938. if (subMatId) {
  28939. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28940. }
  28941. else {
  28942. multiMaterial.subMaterials.push(null);
  28943. }
  28944. }
  28945. return multiMaterial;
  28946. };
  28947. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28948. if (!parsedMaterial.customType) {
  28949. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28950. }
  28951. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28952. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28953. if (!BABYLON.LegacyPBRMaterial) {
  28954. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28955. return;
  28956. }
  28957. }
  28958. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28959. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28960. ;
  28961. };
  28962. // Triangle views
  28963. Material._TriangleFillMode = 0;
  28964. Material._WireFrameFillMode = 1;
  28965. Material._PointFillMode = 2;
  28966. // Draw modes
  28967. Material._PointListDrawMode = 3;
  28968. Material._LineListDrawMode = 4;
  28969. Material._LineLoopDrawMode = 5;
  28970. Material._LineStripDrawMode = 6;
  28971. Material._TriangleStripDrawMode = 7;
  28972. Material._TriangleFanDrawMode = 8;
  28973. Material._ClockWiseSideOrientation = 0;
  28974. Material._CounterClockWiseSideOrientation = 1;
  28975. Material._TextureDirtyFlag = 1;
  28976. Material._LightDirtyFlag = 2;
  28977. Material._FresnelDirtyFlag = 4;
  28978. Material._AttributesDirtyFlag = 8;
  28979. Material._MiscDirtyFlag = 16;
  28980. __decorate([
  28981. BABYLON.serialize()
  28982. ], Material.prototype, "id", void 0);
  28983. __decorate([
  28984. BABYLON.serialize()
  28985. ], Material.prototype, "name", void 0);
  28986. __decorate([
  28987. BABYLON.serialize()
  28988. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28989. __decorate([
  28990. BABYLON.serialize()
  28991. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28992. __decorate([
  28993. BABYLON.serialize()
  28994. ], Material.prototype, "state", void 0);
  28995. __decorate([
  28996. BABYLON.serialize()
  28997. ], Material.prototype, "alpha", void 0);
  28998. __decorate([
  28999. BABYLON.serialize("backFaceCulling")
  29000. ], Material.prototype, "_backFaceCulling", void 0);
  29001. __decorate([
  29002. BABYLON.serialize()
  29003. ], Material.prototype, "sideOrientation", void 0);
  29004. __decorate([
  29005. BABYLON.serialize("alphaMode")
  29006. ], Material.prototype, "_alphaMode", void 0);
  29007. __decorate([
  29008. BABYLON.serialize()
  29009. ], Material.prototype, "_needDepthPrePass", void 0);
  29010. __decorate([
  29011. BABYLON.serialize()
  29012. ], Material.prototype, "disableDepthWrite", void 0);
  29013. __decorate([
  29014. BABYLON.serialize()
  29015. ], Material.prototype, "forceDepthWrite", void 0);
  29016. __decorate([
  29017. BABYLON.serialize()
  29018. ], Material.prototype, "separateCullingPass", void 0);
  29019. __decorate([
  29020. BABYLON.serialize("fogEnabled")
  29021. ], Material.prototype, "_fogEnabled", void 0);
  29022. __decorate([
  29023. BABYLON.serialize()
  29024. ], Material.prototype, "pointSize", void 0);
  29025. __decorate([
  29026. BABYLON.serialize()
  29027. ], Material.prototype, "zOffset", void 0);
  29028. __decorate([
  29029. BABYLON.serialize()
  29030. ], Material.prototype, "wireframe", null);
  29031. __decorate([
  29032. BABYLON.serialize()
  29033. ], Material.prototype, "pointsCloud", null);
  29034. __decorate([
  29035. BABYLON.serialize()
  29036. ], Material.prototype, "fillMode", null);
  29037. return Material;
  29038. }());
  29039. BABYLON.Material = Material;
  29040. })(BABYLON || (BABYLON = {}));
  29041. //# sourceMappingURL=babylon.material.js.map
  29042. var BABYLON;
  29043. (function (BABYLON) {
  29044. var UniformBuffer = /** @class */ (function () {
  29045. /**
  29046. * Uniform buffer objects.
  29047. *
  29048. * Handles blocks of uniform on the GPU.
  29049. *
  29050. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29051. *
  29052. * For more information, please refer to :
  29053. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29054. */
  29055. function UniformBuffer(engine, data, dynamic) {
  29056. this._engine = engine;
  29057. this._noUBO = !engine.supportsUniformBuffers;
  29058. this._dynamic = dynamic;
  29059. this._data = data || [];
  29060. this._uniformLocations = {};
  29061. this._uniformSizes = {};
  29062. this._uniformLocationPointer = 0;
  29063. this._needSync = false;
  29064. if (this._noUBO) {
  29065. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29066. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29067. this.updateFloat = this._updateFloatForEffect;
  29068. this.updateFloat2 = this._updateFloat2ForEffect;
  29069. this.updateFloat3 = this._updateFloat3ForEffect;
  29070. this.updateFloat4 = this._updateFloat4ForEffect;
  29071. this.updateMatrix = this._updateMatrixForEffect;
  29072. this.updateVector3 = this._updateVector3ForEffect;
  29073. this.updateVector4 = this._updateVector4ForEffect;
  29074. this.updateColor3 = this._updateColor3ForEffect;
  29075. this.updateColor4 = this._updateColor4ForEffect;
  29076. }
  29077. else {
  29078. this._engine._uniformBuffers.push(this);
  29079. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29080. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29081. this.updateFloat = this._updateFloatForUniform;
  29082. this.updateFloat2 = this._updateFloat2ForUniform;
  29083. this.updateFloat3 = this._updateFloat3ForUniform;
  29084. this.updateFloat4 = this._updateFloat4ForUniform;
  29085. this.updateMatrix = this._updateMatrixForUniform;
  29086. this.updateVector3 = this._updateVector3ForUniform;
  29087. this.updateVector4 = this._updateVector4ForUniform;
  29088. this.updateColor3 = this._updateColor3ForUniform;
  29089. this.updateColor4 = this._updateColor4ForUniform;
  29090. }
  29091. }
  29092. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29093. // Properties
  29094. /**
  29095. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29096. * or just falling back on setUniformXXX calls.
  29097. */
  29098. get: function () {
  29099. return !this._noUBO;
  29100. },
  29101. enumerable: true,
  29102. configurable: true
  29103. });
  29104. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29105. /**
  29106. * Indicates if the WebGL underlying uniform buffer is in sync
  29107. * with the javascript cache data.
  29108. */
  29109. get: function () {
  29110. return !this._needSync;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. /**
  29116. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29117. * Also, a dynamic UniformBuffer will disable cache verification and always
  29118. * update the underlying WebGL uniform buffer to the GPU.
  29119. */
  29120. UniformBuffer.prototype.isDynamic = function () {
  29121. return this._dynamic !== undefined;
  29122. };
  29123. /**
  29124. * The data cache on JS side.
  29125. */
  29126. UniformBuffer.prototype.getData = function () {
  29127. return this._bufferData;
  29128. };
  29129. /**
  29130. * The underlying WebGL Uniform buffer.
  29131. */
  29132. UniformBuffer.prototype.getBuffer = function () {
  29133. return this._buffer;
  29134. };
  29135. /**
  29136. * std140 layout specifies how to align data within an UBO structure.
  29137. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29138. * for specs.
  29139. */
  29140. UniformBuffer.prototype._fillAlignment = function (size) {
  29141. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29142. // and 4x4 matrices
  29143. // TODO : change if other types are used
  29144. var alignment;
  29145. if (size <= 2) {
  29146. alignment = size;
  29147. }
  29148. else {
  29149. alignment = 4;
  29150. }
  29151. if ((this._uniformLocationPointer % alignment) !== 0) {
  29152. var oldPointer = this._uniformLocationPointer;
  29153. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29154. var diff = this._uniformLocationPointer - oldPointer;
  29155. for (var i = 0; i < diff; i++) {
  29156. this._data.push(0);
  29157. }
  29158. }
  29159. };
  29160. /**
  29161. * Adds an uniform in the buffer.
  29162. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29163. * for the layout to be correct !
  29164. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29165. * @param {number|number[]} size Data size, or data directly.
  29166. */
  29167. UniformBuffer.prototype.addUniform = function (name, size) {
  29168. if (this._noUBO) {
  29169. return;
  29170. }
  29171. if (this._uniformLocations[name] !== undefined) {
  29172. // Already existing uniform
  29173. return;
  29174. }
  29175. // This function must be called in the order of the shader layout !
  29176. // size can be the size of the uniform, or data directly
  29177. var data;
  29178. if (size instanceof Array) {
  29179. data = size;
  29180. size = data.length;
  29181. }
  29182. else {
  29183. size = size;
  29184. data = [];
  29185. // Fill with zeros
  29186. for (var i = 0; i < size; i++) {
  29187. data.push(0);
  29188. }
  29189. }
  29190. this._fillAlignment(size);
  29191. this._uniformSizes[name] = size;
  29192. this._uniformLocations[name] = this._uniformLocationPointer;
  29193. this._uniformLocationPointer += size;
  29194. for (var i = 0; i < size; i++) {
  29195. this._data.push(data[i]);
  29196. }
  29197. this._needSync = true;
  29198. };
  29199. /**
  29200. * Wrapper for addUniform.
  29201. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29202. * @param {Matrix} mat A 4x4 matrix.
  29203. */
  29204. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29205. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29206. };
  29207. /**
  29208. * Wrapper for addUniform.
  29209. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29210. * @param {number} x
  29211. * @param {number} y
  29212. */
  29213. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29214. var temp = [x, y];
  29215. this.addUniform(name, temp);
  29216. };
  29217. /**
  29218. * Wrapper for addUniform.
  29219. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29220. * @param {number} x
  29221. * @param {number} y
  29222. * @param {number} z
  29223. */
  29224. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29225. var temp = [x, y, z];
  29226. this.addUniform(name, temp);
  29227. };
  29228. /**
  29229. * Wrapper for addUniform.
  29230. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29231. * @param {Color3} color
  29232. */
  29233. UniformBuffer.prototype.addColor3 = function (name, color) {
  29234. var temp = new Array();
  29235. color.toArray(temp);
  29236. this.addUniform(name, temp);
  29237. };
  29238. /**
  29239. * Wrapper for addUniform.
  29240. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29241. * @param {Color3} color
  29242. * @param {number} alpha
  29243. */
  29244. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29245. var temp = new Array();
  29246. color.toArray(temp);
  29247. temp.push(alpha);
  29248. this.addUniform(name, temp);
  29249. };
  29250. /**
  29251. * Wrapper for addUniform.
  29252. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29253. * @param {Vector3} vector
  29254. */
  29255. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29256. var temp = new Array();
  29257. vector.toArray(temp);
  29258. this.addUniform(name, temp);
  29259. };
  29260. /**
  29261. * Wrapper for addUniform.
  29262. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29263. */
  29264. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29265. this.addUniform(name, 12);
  29266. };
  29267. /**
  29268. * Wrapper for addUniform.
  29269. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29270. */
  29271. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29272. this.addUniform(name, 8);
  29273. };
  29274. /**
  29275. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29276. */
  29277. UniformBuffer.prototype.create = function () {
  29278. if (this._noUBO) {
  29279. return;
  29280. }
  29281. if (this._buffer) {
  29282. return; // nothing to do
  29283. }
  29284. // See spec, alignment must be filled as a vec4
  29285. this._fillAlignment(4);
  29286. this._bufferData = new Float32Array(this._data);
  29287. this._rebuild();
  29288. this._needSync = true;
  29289. };
  29290. UniformBuffer.prototype._rebuild = function () {
  29291. if (this._noUBO) {
  29292. return;
  29293. }
  29294. if (this._dynamic) {
  29295. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29296. }
  29297. else {
  29298. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29299. }
  29300. };
  29301. /**
  29302. * Updates the WebGL Uniform Buffer on the GPU.
  29303. * If the `dynamic` flag is set to true, no cache comparison is done.
  29304. * Otherwise, the buffer will be updated only if the cache differs.
  29305. */
  29306. UniformBuffer.prototype.update = function () {
  29307. if (!this._buffer) {
  29308. this.create();
  29309. return;
  29310. }
  29311. if (!this._dynamic && !this._needSync) {
  29312. return;
  29313. }
  29314. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29315. this._needSync = false;
  29316. };
  29317. /**
  29318. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29319. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29320. * @param {number[]|Float32Array} data Flattened data
  29321. * @param {number} size Size of the data.
  29322. */
  29323. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29324. var location = this._uniformLocations[uniformName];
  29325. if (location === undefined) {
  29326. if (this._buffer) {
  29327. // Cannot add an uniform if the buffer is already created
  29328. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29329. return;
  29330. }
  29331. this.addUniform(uniformName, size);
  29332. location = this._uniformLocations[uniformName];
  29333. }
  29334. if (!this._buffer) {
  29335. this.create();
  29336. }
  29337. if (!this._dynamic) {
  29338. // Cache for static uniform buffers
  29339. var changed = false;
  29340. for (var i = 0; i < size; i++) {
  29341. if (this._bufferData[location + i] !== data[i]) {
  29342. changed = true;
  29343. this._bufferData[location + i] = data[i];
  29344. }
  29345. }
  29346. this._needSync = this._needSync || changed;
  29347. }
  29348. else {
  29349. // No cache for dynamic
  29350. for (var i = 0; i < size; i++) {
  29351. this._bufferData[location + i] = data[i];
  29352. }
  29353. }
  29354. };
  29355. // Update methods
  29356. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29357. // To match std140, matrix must be realigned
  29358. for (var i = 0; i < 3; i++) {
  29359. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29360. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29361. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29362. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29363. }
  29364. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29365. };
  29366. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29367. this._currentEffect.setMatrix3x3(name, matrix);
  29368. };
  29369. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29370. this._currentEffect.setMatrix2x2(name, matrix);
  29371. };
  29372. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29373. // To match std140, matrix must be realigned
  29374. for (var i = 0; i < 2; i++) {
  29375. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29376. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29377. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29378. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29379. }
  29380. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29381. };
  29382. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29383. this._currentEffect.setFloat(name, x);
  29384. };
  29385. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29386. UniformBuffer._tempBuffer[0] = x;
  29387. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29388. };
  29389. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29390. if (suffix === void 0) { suffix = ""; }
  29391. this._currentEffect.setFloat2(name + suffix, x, y);
  29392. };
  29393. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29394. if (suffix === void 0) { suffix = ""; }
  29395. UniformBuffer._tempBuffer[0] = x;
  29396. UniformBuffer._tempBuffer[1] = y;
  29397. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29398. };
  29399. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29400. if (suffix === void 0) { suffix = ""; }
  29401. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29402. };
  29403. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29404. if (suffix === void 0) { suffix = ""; }
  29405. UniformBuffer._tempBuffer[0] = x;
  29406. UniformBuffer._tempBuffer[1] = y;
  29407. UniformBuffer._tempBuffer[2] = z;
  29408. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29409. };
  29410. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29411. if (suffix === void 0) { suffix = ""; }
  29412. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29413. };
  29414. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29415. if (suffix === void 0) { suffix = ""; }
  29416. UniformBuffer._tempBuffer[0] = x;
  29417. UniformBuffer._tempBuffer[1] = y;
  29418. UniformBuffer._tempBuffer[2] = z;
  29419. UniformBuffer._tempBuffer[3] = w;
  29420. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29421. };
  29422. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29423. this._currentEffect.setMatrix(name, mat);
  29424. };
  29425. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29426. this.updateUniform(name, mat.toArray(), 16);
  29427. };
  29428. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29429. this._currentEffect.setVector3(name, vector);
  29430. };
  29431. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29432. vector.toArray(UniformBuffer._tempBuffer);
  29433. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29434. };
  29435. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29436. this._currentEffect.setVector4(name, vector);
  29437. };
  29438. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29439. vector.toArray(UniformBuffer._tempBuffer);
  29440. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29441. };
  29442. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29443. if (suffix === void 0) { suffix = ""; }
  29444. this._currentEffect.setColor3(name + suffix, color);
  29445. };
  29446. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29447. if (suffix === void 0) { suffix = ""; }
  29448. color.toArray(UniformBuffer._tempBuffer);
  29449. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29450. };
  29451. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29452. if (suffix === void 0) { suffix = ""; }
  29453. this._currentEffect.setColor4(name + suffix, color, alpha);
  29454. };
  29455. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29456. if (suffix === void 0) { suffix = ""; }
  29457. color.toArray(UniformBuffer._tempBuffer);
  29458. UniformBuffer._tempBuffer[3] = alpha;
  29459. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29460. };
  29461. /**
  29462. * Sets a sampler uniform on the effect.
  29463. * @param {string} name Name of the sampler.
  29464. * @param {Texture} texture
  29465. */
  29466. UniformBuffer.prototype.setTexture = function (name, texture) {
  29467. this._currentEffect.setTexture(name, texture);
  29468. };
  29469. /**
  29470. * Directly updates the value of the uniform in the cache AND on the GPU.
  29471. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29472. * @param {number[]|Float32Array} data Flattened data
  29473. */
  29474. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29475. this.updateUniform(uniformName, data, data.length);
  29476. this.update();
  29477. };
  29478. /**
  29479. * Binds this uniform buffer to an effect.
  29480. * @param {Effect} effect
  29481. * @param {string} name Name of the uniform block in the shader.
  29482. */
  29483. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29484. this._currentEffect = effect;
  29485. if (this._noUBO || !this._buffer) {
  29486. return;
  29487. }
  29488. effect.bindUniformBuffer(this._buffer, name);
  29489. };
  29490. /**
  29491. * Disposes the uniform buffer.
  29492. */
  29493. UniformBuffer.prototype.dispose = function () {
  29494. if (this._noUBO) {
  29495. return;
  29496. }
  29497. var index = this._engine._uniformBuffers.indexOf(this);
  29498. if (index !== -1) {
  29499. this._engine._uniformBuffers.splice(index, 1);
  29500. }
  29501. if (!this._buffer) {
  29502. return;
  29503. }
  29504. if (this._engine._releaseBuffer(this._buffer)) {
  29505. this._buffer = null;
  29506. }
  29507. };
  29508. // Pool for avoiding memory leaks
  29509. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29510. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29511. return UniformBuffer;
  29512. }());
  29513. BABYLON.UniformBuffer = UniformBuffer;
  29514. })(BABYLON || (BABYLON = {}));
  29515. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29516. var BABYLON;
  29517. (function (BABYLON) {
  29518. var VertexData = /** @class */ (function () {
  29519. function VertexData() {
  29520. }
  29521. VertexData.prototype.set = function (data, kind) {
  29522. switch (kind) {
  29523. case BABYLON.VertexBuffer.PositionKind:
  29524. this.positions = data;
  29525. break;
  29526. case BABYLON.VertexBuffer.NormalKind:
  29527. this.normals = data;
  29528. break;
  29529. case BABYLON.VertexBuffer.TangentKind:
  29530. this.tangents = data;
  29531. break;
  29532. case BABYLON.VertexBuffer.UVKind:
  29533. this.uvs = data;
  29534. break;
  29535. case BABYLON.VertexBuffer.UV2Kind:
  29536. this.uvs2 = data;
  29537. break;
  29538. case BABYLON.VertexBuffer.UV3Kind:
  29539. this.uvs3 = data;
  29540. break;
  29541. case BABYLON.VertexBuffer.UV4Kind:
  29542. this.uvs4 = data;
  29543. break;
  29544. case BABYLON.VertexBuffer.UV5Kind:
  29545. this.uvs5 = data;
  29546. break;
  29547. case BABYLON.VertexBuffer.UV6Kind:
  29548. this.uvs6 = data;
  29549. break;
  29550. case BABYLON.VertexBuffer.ColorKind:
  29551. this.colors = data;
  29552. break;
  29553. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29554. this.matricesIndices = data;
  29555. break;
  29556. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29557. this.matricesWeights = data;
  29558. break;
  29559. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29560. this.matricesIndicesExtra = data;
  29561. break;
  29562. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29563. this.matricesWeightsExtra = data;
  29564. break;
  29565. }
  29566. };
  29567. /**
  29568. * Associates the vertexData to the passed Mesh.
  29569. * Sets it as updatable or not (default `false`).
  29570. * Returns the VertexData.
  29571. */
  29572. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29573. this._applyTo(mesh, updatable);
  29574. return this;
  29575. };
  29576. /**
  29577. * Associates the vertexData to the passed Geometry.
  29578. * Sets it as updatable or not (default `false`).
  29579. * Returns the VertexData.
  29580. */
  29581. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29582. this._applyTo(geometry, updatable);
  29583. return this;
  29584. };
  29585. /**
  29586. * Updates the associated mesh.
  29587. * Returns the VertexData.
  29588. */
  29589. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29590. this._update(mesh);
  29591. return this;
  29592. };
  29593. /**
  29594. * Updates the associated geometry.
  29595. * Returns the VertexData.
  29596. */
  29597. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29598. this._update(geometry);
  29599. return this;
  29600. };
  29601. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29602. if (updatable === void 0) { updatable = false; }
  29603. if (this.positions) {
  29604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29605. }
  29606. if (this.normals) {
  29607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29608. }
  29609. if (this.tangents) {
  29610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29611. }
  29612. if (this.uvs) {
  29613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29614. }
  29615. if (this.uvs2) {
  29616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29617. }
  29618. if (this.uvs3) {
  29619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29620. }
  29621. if (this.uvs4) {
  29622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29623. }
  29624. if (this.uvs5) {
  29625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29626. }
  29627. if (this.uvs6) {
  29628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29629. }
  29630. if (this.colors) {
  29631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29632. }
  29633. if (this.matricesIndices) {
  29634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29635. }
  29636. if (this.matricesWeights) {
  29637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29638. }
  29639. if (this.matricesIndicesExtra) {
  29640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29641. }
  29642. if (this.matricesWeightsExtra) {
  29643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29644. }
  29645. if (this.indices) {
  29646. meshOrGeometry.setIndices(this.indices, null, updatable);
  29647. }
  29648. return this;
  29649. };
  29650. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29651. if (this.positions) {
  29652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29653. }
  29654. if (this.normals) {
  29655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29656. }
  29657. if (this.tangents) {
  29658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29659. }
  29660. if (this.uvs) {
  29661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29662. }
  29663. if (this.uvs2) {
  29664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29665. }
  29666. if (this.uvs3) {
  29667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29668. }
  29669. if (this.uvs4) {
  29670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29671. }
  29672. if (this.uvs5) {
  29673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29674. }
  29675. if (this.uvs6) {
  29676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29677. }
  29678. if (this.colors) {
  29679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29680. }
  29681. if (this.matricesIndices) {
  29682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29683. }
  29684. if (this.matricesWeights) {
  29685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29686. }
  29687. if (this.matricesIndicesExtra) {
  29688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29689. }
  29690. if (this.matricesWeightsExtra) {
  29691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29692. }
  29693. if (this.indices) {
  29694. meshOrGeometry.setIndices(this.indices, null);
  29695. }
  29696. return this;
  29697. };
  29698. /**
  29699. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29700. * Returns the VertexData.
  29701. */
  29702. VertexData.prototype.transform = function (matrix) {
  29703. var transformed = BABYLON.Vector3.Zero();
  29704. var index;
  29705. if (this.positions) {
  29706. var position = BABYLON.Vector3.Zero();
  29707. for (index = 0; index < this.positions.length; index += 3) {
  29708. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29709. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29710. this.positions[index] = transformed.x;
  29711. this.positions[index + 1] = transformed.y;
  29712. this.positions[index + 2] = transformed.z;
  29713. }
  29714. }
  29715. if (this.normals) {
  29716. var normal = BABYLON.Vector3.Zero();
  29717. for (index = 0; index < this.normals.length; index += 3) {
  29718. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29719. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29720. this.normals[index] = transformed.x;
  29721. this.normals[index + 1] = transformed.y;
  29722. this.normals[index + 2] = transformed.z;
  29723. }
  29724. }
  29725. if (this.tangents) {
  29726. var tangent = BABYLON.Vector4.Zero();
  29727. var tangentTransformed = BABYLON.Vector4.Zero();
  29728. for (index = 0; index < this.tangents.length; index += 4) {
  29729. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29730. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29731. this.tangents[index] = tangentTransformed.x;
  29732. this.tangents[index + 1] = tangentTransformed.y;
  29733. this.tangents[index + 2] = tangentTransformed.z;
  29734. this.tangents[index + 3] = tangentTransformed.w;
  29735. }
  29736. }
  29737. return this;
  29738. };
  29739. /**
  29740. * Merges the passed VertexData into the current one.
  29741. * Returns the modified VertexData.
  29742. */
  29743. VertexData.prototype.merge = function (other, options) {
  29744. options = options || {};
  29745. if (other.indices) {
  29746. if (!this.indices) {
  29747. this.indices = [];
  29748. }
  29749. var offset = this.positions ? this.positions.length / 3 : 0;
  29750. for (var index = 0; index < other.indices.length; index++) {
  29751. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29752. this.indices.push(other.indices[index] + offset);
  29753. }
  29754. }
  29755. this.positions = this._mergeElement(this.positions, other.positions);
  29756. if (!this.positions) {
  29757. return this;
  29758. }
  29759. var count = this.positions.length / 3;
  29760. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29761. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29762. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29763. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29764. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29765. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29766. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29767. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29768. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29769. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29770. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29771. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29772. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29773. return this;
  29774. };
  29775. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29776. if (length === void 0) { length = 0; }
  29777. if (defaultValue === void 0) { defaultValue = 0; }
  29778. if (!other && !source) {
  29779. return null;
  29780. }
  29781. if (!other) {
  29782. var padding = new Float32Array(source.length);
  29783. padding.fill(defaultValue);
  29784. return this._mergeElement(source, padding, length);
  29785. }
  29786. if (!source) {
  29787. if (length === 0 || length === other.length) {
  29788. return other;
  29789. }
  29790. var padding = new Float32Array(length - other.length);
  29791. padding.fill(defaultValue);
  29792. return this._mergeElement(padding, other, length);
  29793. }
  29794. var len = other.length + source.length;
  29795. var isSrcTypedArray = source instanceof Float32Array;
  29796. var isOthTypedArray = other instanceof Float32Array;
  29797. // use non-loop method when the source is Float32Array
  29798. if (isSrcTypedArray) {
  29799. var ret32 = new Float32Array(len);
  29800. ret32.set(source);
  29801. ret32.set(other, source.length);
  29802. return ret32;
  29803. // source is number[], when other is also use concat
  29804. }
  29805. else if (!isOthTypedArray) {
  29806. return source.concat(other);
  29807. // source is a number[], but other is a Float32Array, loop required
  29808. }
  29809. else {
  29810. var ret = source.slice(0); // copy source to a separate array
  29811. for (var i = 0, len = other.length; i < len; i++) {
  29812. ret.push(other[i]);
  29813. }
  29814. return ret;
  29815. }
  29816. };
  29817. /**
  29818. * Serializes the VertexData.
  29819. * Returns a serialized object.
  29820. */
  29821. VertexData.prototype.serialize = function () {
  29822. var serializationObject = this.serialize();
  29823. if (this.positions) {
  29824. serializationObject.positions = this.positions;
  29825. }
  29826. if (this.normals) {
  29827. serializationObject.normals = this.normals;
  29828. }
  29829. if (this.tangents) {
  29830. serializationObject.tangents = this.tangents;
  29831. }
  29832. if (this.uvs) {
  29833. serializationObject.uvs = this.uvs;
  29834. }
  29835. if (this.uvs2) {
  29836. serializationObject.uvs2 = this.uvs2;
  29837. }
  29838. if (this.uvs3) {
  29839. serializationObject.uvs3 = this.uvs3;
  29840. }
  29841. if (this.uvs4) {
  29842. serializationObject.uvs4 = this.uvs4;
  29843. }
  29844. if (this.uvs5) {
  29845. serializationObject.uvs5 = this.uvs5;
  29846. }
  29847. if (this.uvs6) {
  29848. serializationObject.uvs6 = this.uvs6;
  29849. }
  29850. if (this.colors) {
  29851. serializationObject.colors = this.colors;
  29852. }
  29853. if (this.matricesIndices) {
  29854. serializationObject.matricesIndices = this.matricesIndices;
  29855. serializationObject.matricesIndices._isExpanded = true;
  29856. }
  29857. if (this.matricesWeights) {
  29858. serializationObject.matricesWeights = this.matricesWeights;
  29859. }
  29860. if (this.matricesIndicesExtra) {
  29861. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29862. serializationObject.matricesIndicesExtra._isExpanded = true;
  29863. }
  29864. if (this.matricesWeightsExtra) {
  29865. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29866. }
  29867. serializationObject.indices = this.indices;
  29868. return serializationObject;
  29869. };
  29870. // Statics
  29871. /**
  29872. * Returns the object VertexData associated to the passed mesh.
  29873. */
  29874. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29875. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29876. };
  29877. /**
  29878. * Returns the object VertexData associated to the passed geometry.
  29879. */
  29880. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29881. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29882. };
  29883. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29884. var result = new VertexData();
  29885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29886. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29887. }
  29888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29889. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29890. }
  29891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29892. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29893. }
  29894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29895. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29896. }
  29897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29898. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29899. }
  29900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29901. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29902. }
  29903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29904. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29905. }
  29906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29907. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29908. }
  29909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29910. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29911. }
  29912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29913. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29914. }
  29915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29916. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29917. }
  29918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29919. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29920. }
  29921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29922. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29923. }
  29924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29925. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29926. }
  29927. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29928. return result;
  29929. };
  29930. /**
  29931. * Creates the vertexData of the Ribbon.
  29932. */
  29933. VertexData.CreateRibbon = function (options) {
  29934. var pathArray = options.pathArray;
  29935. var closeArray = options.closeArray || false;
  29936. var closePath = options.closePath || false;
  29937. var invertUV = options.invertUV || false;
  29938. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29939. var offset = options.offset || defaultOffset;
  29940. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29941. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29942. var customUV = options.uvs;
  29943. var customColors = options.colors;
  29944. var positions = [];
  29945. var indices = [];
  29946. var normals = [];
  29947. var uvs = [];
  29948. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29949. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29950. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29951. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29952. var minlg; // minimal length among all paths from pathArray
  29953. var lg = []; // array of path lengths : nb of vertex per path
  29954. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29955. var p; // path iterator
  29956. var i; // point iterator
  29957. var j; // point iterator
  29958. // if single path in pathArray
  29959. if (pathArray.length < 2) {
  29960. var ar1 = [];
  29961. var ar2 = [];
  29962. for (i = 0; i < pathArray[0].length - offset; i++) {
  29963. ar1.push(pathArray[0][i]);
  29964. ar2.push(pathArray[0][i + offset]);
  29965. }
  29966. pathArray = [ar1, ar2];
  29967. }
  29968. // positions and horizontal distances (u)
  29969. var idc = 0;
  29970. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29971. var path;
  29972. var l;
  29973. minlg = pathArray[0].length;
  29974. var vectlg;
  29975. var dist;
  29976. for (p = 0; p < pathArray.length; p++) {
  29977. uTotalDistance[p] = 0;
  29978. us[p] = [0];
  29979. path = pathArray[p];
  29980. l = path.length;
  29981. minlg = (minlg < l) ? minlg : l;
  29982. j = 0;
  29983. while (j < l) {
  29984. positions.push(path[j].x, path[j].y, path[j].z);
  29985. if (j > 0) {
  29986. vectlg = path[j].subtract(path[j - 1]).length();
  29987. dist = vectlg + uTotalDistance[p];
  29988. us[p].push(dist);
  29989. uTotalDistance[p] = dist;
  29990. }
  29991. j++;
  29992. }
  29993. if (closePath) {
  29994. j--;
  29995. positions.push(path[0].x, path[0].y, path[0].z);
  29996. vectlg = path[j].subtract(path[0]).length();
  29997. dist = vectlg + uTotalDistance[p];
  29998. us[p].push(dist);
  29999. uTotalDistance[p] = dist;
  30000. }
  30001. lg[p] = l + closePathCorr;
  30002. idx[p] = idc;
  30003. idc += (l + closePathCorr);
  30004. }
  30005. // vertical distances (v)
  30006. var path1;
  30007. var path2;
  30008. var vertex1 = null;
  30009. var vertex2 = null;
  30010. for (i = 0; i < minlg + closePathCorr; i++) {
  30011. vTotalDistance[i] = 0;
  30012. vs[i] = [0];
  30013. for (p = 0; p < pathArray.length - 1; p++) {
  30014. path1 = pathArray[p];
  30015. path2 = pathArray[p + 1];
  30016. if (i === minlg) {
  30017. vertex1 = path1[0];
  30018. vertex2 = path2[0];
  30019. }
  30020. else {
  30021. vertex1 = path1[i];
  30022. vertex2 = path2[i];
  30023. }
  30024. vectlg = vertex2.subtract(vertex1).length();
  30025. dist = vectlg + vTotalDistance[i];
  30026. vs[i].push(dist);
  30027. vTotalDistance[i] = dist;
  30028. }
  30029. if (closeArray && vertex2 && vertex1) {
  30030. path1 = pathArray[p];
  30031. path2 = pathArray[0];
  30032. if (i === minlg) {
  30033. vertex2 = path2[0];
  30034. }
  30035. vectlg = vertex2.subtract(vertex1).length();
  30036. dist = vectlg + vTotalDistance[i];
  30037. vTotalDistance[i] = dist;
  30038. }
  30039. }
  30040. // uvs
  30041. var u;
  30042. var v;
  30043. if (customUV) {
  30044. for (p = 0; p < customUV.length; p++) {
  30045. uvs.push(customUV[p].x, customUV[p].y);
  30046. }
  30047. }
  30048. else {
  30049. for (p = 0; p < pathArray.length; p++) {
  30050. for (i = 0; i < minlg + closePathCorr; i++) {
  30051. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30052. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30053. if (invertUV) {
  30054. uvs.push(v, u);
  30055. }
  30056. else {
  30057. uvs.push(u, v);
  30058. }
  30059. }
  30060. }
  30061. }
  30062. // indices
  30063. p = 0; // path index
  30064. var pi = 0; // positions array index
  30065. var l1 = lg[p] - 1; // path1 length
  30066. var l2 = lg[p + 1] - 1; // path2 length
  30067. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30068. var shft = idx[1] - idx[0]; // shift
  30069. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30070. while (pi <= min && p < path1nb) {
  30071. // 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
  30072. indices.push(pi, pi + shft, pi + 1);
  30073. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30074. pi += 1;
  30075. if (pi === min) {
  30076. p++;
  30077. if (p === lg.length - 1) {
  30078. shft = idx[0] - idx[p];
  30079. l1 = lg[p] - 1;
  30080. l2 = lg[0] - 1;
  30081. }
  30082. else {
  30083. shft = idx[p + 1] - idx[p];
  30084. l1 = lg[p] - 1;
  30085. l2 = lg[p + 1] - 1;
  30086. }
  30087. pi = idx[p];
  30088. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30089. }
  30090. }
  30091. // normals
  30092. VertexData.ComputeNormals(positions, indices, normals);
  30093. if (closePath) {
  30094. var indexFirst = 0;
  30095. var indexLast = 0;
  30096. for (p = 0; p < pathArray.length; p++) {
  30097. indexFirst = idx[p] * 3;
  30098. if (p + 1 < pathArray.length) {
  30099. indexLast = (idx[p + 1] - 1) * 3;
  30100. }
  30101. else {
  30102. indexLast = normals.length - 3;
  30103. }
  30104. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30105. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30106. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30107. normals[indexLast] = normals[indexFirst];
  30108. normals[indexLast + 1] = normals[indexFirst + 1];
  30109. normals[indexLast + 2] = normals[indexFirst + 2];
  30110. }
  30111. }
  30112. // sides
  30113. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30114. // Colors
  30115. var colors = null;
  30116. if (customColors) {
  30117. colors = new Float32Array(customColors.length * 4);
  30118. for (var c = 0; c < customColors.length; c++) {
  30119. colors[c * 4] = customColors[c].r;
  30120. colors[c * 4 + 1] = customColors[c].g;
  30121. colors[c * 4 + 2] = customColors[c].b;
  30122. colors[c * 4 + 3] = customColors[c].a;
  30123. }
  30124. }
  30125. // Result
  30126. var vertexData = new VertexData();
  30127. var positions32 = new Float32Array(positions);
  30128. var normals32 = new Float32Array(normals);
  30129. var uvs32 = new Float32Array(uvs);
  30130. vertexData.indices = indices;
  30131. vertexData.positions = positions32;
  30132. vertexData.normals = normals32;
  30133. vertexData.uvs = uvs32;
  30134. if (colors) {
  30135. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30136. }
  30137. if (closePath) {
  30138. vertexData._idx = idx;
  30139. }
  30140. return vertexData;
  30141. };
  30142. /**
  30143. * Creates the VertexData of the Box.
  30144. */
  30145. VertexData.CreateBox = function (options) {
  30146. var normalsSource = [
  30147. new BABYLON.Vector3(0, 0, 1),
  30148. new BABYLON.Vector3(0, 0, -1),
  30149. new BABYLON.Vector3(1, 0, 0),
  30150. new BABYLON.Vector3(-1, 0, 0),
  30151. new BABYLON.Vector3(0, 1, 0),
  30152. new BABYLON.Vector3(0, -1, 0)
  30153. ];
  30154. var indices = [];
  30155. var positions = [];
  30156. var normals = [];
  30157. var uvs = [];
  30158. var width = options.width || options.size || 1;
  30159. var height = options.height || options.size || 1;
  30160. var depth = options.depth || options.size || 1;
  30161. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30162. var faceUV = options.faceUV || new Array(6);
  30163. var faceColors = options.faceColors;
  30164. var colors = [];
  30165. // default face colors and UV if undefined
  30166. for (var f = 0; f < 6; f++) {
  30167. if (faceUV[f] === undefined) {
  30168. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30169. }
  30170. if (faceColors && faceColors[f] === undefined) {
  30171. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30172. }
  30173. }
  30174. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30175. // Create each face in turn.
  30176. for (var index = 0; index < normalsSource.length; index++) {
  30177. var normal = normalsSource[index];
  30178. // Get two vectors perpendicular to the face normal and to each other.
  30179. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30180. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30181. // Six indices (two triangles) per face.
  30182. var verticesLength = positions.length / 3;
  30183. indices.push(verticesLength);
  30184. indices.push(verticesLength + 1);
  30185. indices.push(verticesLength + 2);
  30186. indices.push(verticesLength);
  30187. indices.push(verticesLength + 2);
  30188. indices.push(verticesLength + 3);
  30189. // Four vertices per face.
  30190. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30191. positions.push(vertex.x, vertex.y, vertex.z);
  30192. normals.push(normal.x, normal.y, normal.z);
  30193. uvs.push(faceUV[index].z, faceUV[index].w);
  30194. if (faceColors) {
  30195. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30196. }
  30197. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30198. positions.push(vertex.x, vertex.y, vertex.z);
  30199. normals.push(normal.x, normal.y, normal.z);
  30200. uvs.push(faceUV[index].x, faceUV[index].w);
  30201. if (faceColors) {
  30202. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30203. }
  30204. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30205. positions.push(vertex.x, vertex.y, vertex.z);
  30206. normals.push(normal.x, normal.y, normal.z);
  30207. uvs.push(faceUV[index].x, faceUV[index].y);
  30208. if (faceColors) {
  30209. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30210. }
  30211. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30212. positions.push(vertex.x, vertex.y, vertex.z);
  30213. normals.push(normal.x, normal.y, normal.z);
  30214. uvs.push(faceUV[index].z, faceUV[index].y);
  30215. if (faceColors) {
  30216. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30217. }
  30218. }
  30219. // sides
  30220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30221. // Result
  30222. var vertexData = new VertexData();
  30223. vertexData.indices = indices;
  30224. vertexData.positions = positions;
  30225. vertexData.normals = normals;
  30226. vertexData.uvs = uvs;
  30227. if (faceColors) {
  30228. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30229. vertexData.colors = totalColors;
  30230. }
  30231. return vertexData;
  30232. };
  30233. /**
  30234. * Creates the VertexData of the Sphere.
  30235. */
  30236. VertexData.CreateSphere = function (options) {
  30237. var segments = options.segments || 32;
  30238. var diameterX = options.diameterX || options.diameter || 1;
  30239. var diameterY = options.diameterY || options.diameter || 1;
  30240. var diameterZ = options.diameterZ || options.diameter || 1;
  30241. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30242. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30243. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30244. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30245. var totalZRotationSteps = 2 + segments;
  30246. var totalYRotationSteps = 2 * totalZRotationSteps;
  30247. var indices = [];
  30248. var positions = [];
  30249. var normals = [];
  30250. var uvs = [];
  30251. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30252. var normalizedZ = zRotationStep / totalZRotationSteps;
  30253. var angleZ = normalizedZ * Math.PI * slice;
  30254. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30255. var normalizedY = yRotationStep / totalYRotationSteps;
  30256. var angleY = normalizedY * Math.PI * 2 * arc;
  30257. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30258. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30259. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30260. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30261. var vertex = complete.multiply(radius);
  30262. var normal = complete.divide(radius).normalize();
  30263. positions.push(vertex.x, vertex.y, vertex.z);
  30264. normals.push(normal.x, normal.y, normal.z);
  30265. uvs.push(normalizedY, normalizedZ);
  30266. }
  30267. if (zRotationStep > 0) {
  30268. var verticesCount = positions.length / 3;
  30269. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30270. indices.push((firstIndex));
  30271. indices.push((firstIndex + 1));
  30272. indices.push(firstIndex + totalYRotationSteps + 1);
  30273. indices.push((firstIndex + totalYRotationSteps + 1));
  30274. indices.push((firstIndex + 1));
  30275. indices.push((firstIndex + totalYRotationSteps + 2));
  30276. }
  30277. }
  30278. }
  30279. // Sides
  30280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30281. // Result
  30282. var vertexData = new VertexData();
  30283. vertexData.indices = indices;
  30284. vertexData.positions = positions;
  30285. vertexData.normals = normals;
  30286. vertexData.uvs = uvs;
  30287. return vertexData;
  30288. };
  30289. /**
  30290. * Creates the VertexData of the Cylinder or Cone.
  30291. */
  30292. VertexData.CreateCylinder = function (options) {
  30293. var height = options.height || 2;
  30294. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30295. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30296. var tessellation = options.tessellation || 24;
  30297. var subdivisions = options.subdivisions || 1;
  30298. var hasRings = options.hasRings ? true : false;
  30299. var enclose = options.enclose ? true : false;
  30300. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30302. var faceUV = options.faceUV || new Array(3);
  30303. var faceColors = options.faceColors;
  30304. // default face colors and UV if undefined
  30305. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30306. var ringNb = (hasRings) ? subdivisions : 1;
  30307. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30308. var f;
  30309. for (f = 0; f < surfaceNb; f++) {
  30310. if (faceColors && faceColors[f] === undefined) {
  30311. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30312. }
  30313. }
  30314. for (f = 0; f < surfaceNb; f++) {
  30315. if (faceUV && faceUV[f] === undefined) {
  30316. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30317. }
  30318. }
  30319. var indices = new Array();
  30320. var positions = new Array();
  30321. var normals = new Array();
  30322. var uvs = new Array();
  30323. var colors = new Array();
  30324. var angle_step = Math.PI * 2 * arc / tessellation;
  30325. var angle;
  30326. var h;
  30327. var radius;
  30328. var tan = (diameterBottom - diameterTop) / 2 / height;
  30329. var ringVertex = BABYLON.Vector3.Zero();
  30330. var ringNormal = BABYLON.Vector3.Zero();
  30331. var ringFirstVertex = BABYLON.Vector3.Zero();
  30332. var ringFirstNormal = BABYLON.Vector3.Zero();
  30333. var quadNormal = BABYLON.Vector3.Zero();
  30334. var Y = BABYLON.Axis.Y;
  30335. // positions, normals, uvs
  30336. var i;
  30337. var j;
  30338. var r;
  30339. var ringIdx = 1;
  30340. var s = 1; // surface index
  30341. var cs = 0;
  30342. var v = 0;
  30343. for (i = 0; i <= subdivisions; i++) {
  30344. h = i / subdivisions;
  30345. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30346. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30347. for (r = 0; r < ringIdx; r++) {
  30348. if (hasRings) {
  30349. s += r;
  30350. }
  30351. if (enclose) {
  30352. s += 2 * r;
  30353. }
  30354. for (j = 0; j <= tessellation; j++) {
  30355. angle = j * angle_step;
  30356. // position
  30357. ringVertex.x = Math.cos(-angle) * radius;
  30358. ringVertex.y = -height / 2 + h * height;
  30359. ringVertex.z = Math.sin(-angle) * radius;
  30360. // normal
  30361. if (diameterTop === 0 && i === subdivisions) {
  30362. // if no top cap, reuse former normals
  30363. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30364. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30365. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30366. }
  30367. else {
  30368. ringNormal.x = ringVertex.x;
  30369. ringNormal.z = ringVertex.z;
  30370. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30371. ringNormal.normalize();
  30372. }
  30373. // keep first ring vertex values for enclose
  30374. if (j === 0) {
  30375. ringFirstVertex.copyFrom(ringVertex);
  30376. ringFirstNormal.copyFrom(ringNormal);
  30377. }
  30378. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30379. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30380. if (hasRings) {
  30381. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30382. }
  30383. else {
  30384. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30385. }
  30386. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30387. if (faceColors) {
  30388. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30389. }
  30390. }
  30391. // if enclose, add four vertices and their dedicated normals
  30392. if (arc !== 1 && enclose) {
  30393. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30394. positions.push(0, ringVertex.y, 0);
  30395. positions.push(0, ringVertex.y, 0);
  30396. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30397. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30398. quadNormal.normalize();
  30399. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30400. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30401. quadNormal.normalize();
  30402. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30403. if (hasRings) {
  30404. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30405. }
  30406. else {
  30407. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30408. }
  30409. uvs.push(faceUV[s + 1].x, v);
  30410. uvs.push(faceUV[s + 1].z, v);
  30411. if (hasRings) {
  30412. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30413. }
  30414. else {
  30415. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30416. }
  30417. uvs.push(faceUV[s + 2].x, v);
  30418. uvs.push(faceUV[s + 2].z, v);
  30419. if (faceColors) {
  30420. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30421. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30422. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30423. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30424. }
  30425. }
  30426. if (cs !== s) {
  30427. cs = s;
  30428. }
  30429. }
  30430. }
  30431. // indices
  30432. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30433. var s;
  30434. i = 0;
  30435. for (s = 0; s < subdivisions; s++) {
  30436. var i0 = 0;
  30437. var i1 = 0;
  30438. var i2 = 0;
  30439. var i3 = 0;
  30440. for (j = 0; j < tessellation; j++) {
  30441. i0 = i * (e + 1) + j;
  30442. i1 = (i + 1) * (e + 1) + j;
  30443. i2 = i * (e + 1) + (j + 1);
  30444. i3 = (i + 1) * (e + 1) + (j + 1);
  30445. indices.push(i0, i1, i2);
  30446. indices.push(i3, i2, i1);
  30447. }
  30448. if (arc !== 1 && enclose) {
  30449. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30450. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30451. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30452. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30453. }
  30454. i = (hasRings) ? (i + 2) : (i + 1);
  30455. }
  30456. // Caps
  30457. var createCylinderCap = function (isTop) {
  30458. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30459. if (radius === 0) {
  30460. return;
  30461. }
  30462. // Cap positions, normals & uvs
  30463. var angle;
  30464. var circleVector;
  30465. var i;
  30466. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30467. var c = null;
  30468. if (faceColors) {
  30469. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30470. }
  30471. // cap center
  30472. var vbase = positions.length / 3;
  30473. var offset = isTop ? height / 2 : -height / 2;
  30474. var center = new BABYLON.Vector3(0, offset, 0);
  30475. positions.push(center.x, center.y, center.z);
  30476. normals.push(0, isTop ? 1 : -1, 0);
  30477. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30478. if (c) {
  30479. colors.push(c.r, c.g, c.b, c.a);
  30480. }
  30481. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30482. for (i = 0; i <= tessellation; i++) {
  30483. angle = Math.PI * 2 * i * arc / tessellation;
  30484. var cos = Math.cos(-angle);
  30485. var sin = Math.sin(-angle);
  30486. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30487. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30488. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30489. normals.push(0, isTop ? 1 : -1, 0);
  30490. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30491. if (c) {
  30492. colors.push(c.r, c.g, c.b, c.a);
  30493. }
  30494. }
  30495. // Cap indices
  30496. for (i = 0; i < tessellation; i++) {
  30497. if (!isTop) {
  30498. indices.push(vbase);
  30499. indices.push(vbase + (i + 1));
  30500. indices.push(vbase + (i + 2));
  30501. }
  30502. else {
  30503. indices.push(vbase);
  30504. indices.push(vbase + (i + 2));
  30505. indices.push(vbase + (i + 1));
  30506. }
  30507. }
  30508. };
  30509. // add caps to geometry
  30510. createCylinderCap(false);
  30511. createCylinderCap(true);
  30512. // Sides
  30513. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30514. var vertexData = new VertexData();
  30515. vertexData.indices = indices;
  30516. vertexData.positions = positions;
  30517. vertexData.normals = normals;
  30518. vertexData.uvs = uvs;
  30519. if (faceColors) {
  30520. vertexData.colors = colors;
  30521. }
  30522. return vertexData;
  30523. };
  30524. /**
  30525. * Creates the VertexData of the Torus.
  30526. */
  30527. VertexData.CreateTorus = function (options) {
  30528. var indices = [];
  30529. var positions = [];
  30530. var normals = [];
  30531. var uvs = [];
  30532. var diameter = options.diameter || 1;
  30533. var thickness = options.thickness || 0.5;
  30534. var tessellation = options.tessellation || 16;
  30535. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30536. var stride = tessellation + 1;
  30537. for (var i = 0; i <= tessellation; i++) {
  30538. var u = i / tessellation;
  30539. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30540. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30541. for (var j = 0; j <= tessellation; j++) {
  30542. var v = 1 - j / tessellation;
  30543. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30544. var dx = Math.cos(innerAngle);
  30545. var dy = Math.sin(innerAngle);
  30546. // Create a vertex.
  30547. var normal = new BABYLON.Vector3(dx, dy, 0);
  30548. var position = normal.scale(thickness / 2);
  30549. var textureCoordinate = new BABYLON.Vector2(u, v);
  30550. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30551. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30552. positions.push(position.x, position.y, position.z);
  30553. normals.push(normal.x, normal.y, normal.z);
  30554. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30555. // And create indices for two triangles.
  30556. var nextI = (i + 1) % stride;
  30557. var nextJ = (j + 1) % stride;
  30558. indices.push(i * stride + j);
  30559. indices.push(i * stride + nextJ);
  30560. indices.push(nextI * stride + j);
  30561. indices.push(i * stride + nextJ);
  30562. indices.push(nextI * stride + nextJ);
  30563. indices.push(nextI * stride + j);
  30564. }
  30565. }
  30566. // Sides
  30567. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30568. // Result
  30569. var vertexData = new VertexData();
  30570. vertexData.indices = indices;
  30571. vertexData.positions = positions;
  30572. vertexData.normals = normals;
  30573. vertexData.uvs = uvs;
  30574. return vertexData;
  30575. };
  30576. /**
  30577. * Creates the VertexData of the LineSystem.
  30578. */
  30579. VertexData.CreateLineSystem = function (options) {
  30580. var indices = [];
  30581. var positions = [];
  30582. var lines = options.lines;
  30583. var colors = options.colors;
  30584. var vertexColors = [];
  30585. var idx = 0;
  30586. for (var l = 0; l < lines.length; l++) {
  30587. var points = lines[l];
  30588. for (var index = 0; index < points.length; index++) {
  30589. positions.push(points[index].x, points[index].y, points[index].z);
  30590. if (colors) {
  30591. var color = colors[l];
  30592. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30593. }
  30594. if (index > 0) {
  30595. indices.push(idx - 1);
  30596. indices.push(idx);
  30597. }
  30598. idx++;
  30599. }
  30600. }
  30601. var vertexData = new VertexData();
  30602. vertexData.indices = indices;
  30603. vertexData.positions = positions;
  30604. if (colors) {
  30605. vertexData.colors = vertexColors;
  30606. }
  30607. return vertexData;
  30608. };
  30609. /**
  30610. * Create the VertexData of the DashedLines.
  30611. */
  30612. VertexData.CreateDashedLines = function (options) {
  30613. var dashSize = options.dashSize || 3;
  30614. var gapSize = options.gapSize || 1;
  30615. var dashNb = options.dashNb || 200;
  30616. var points = options.points;
  30617. var positions = new Array();
  30618. var indices = new Array();
  30619. var curvect = BABYLON.Vector3.Zero();
  30620. var lg = 0;
  30621. var nb = 0;
  30622. var shft = 0;
  30623. var dashshft = 0;
  30624. var curshft = 0;
  30625. var idx = 0;
  30626. var i = 0;
  30627. for (i = 0; i < points.length - 1; i++) {
  30628. points[i + 1].subtractToRef(points[i], curvect);
  30629. lg += curvect.length();
  30630. }
  30631. shft = lg / dashNb;
  30632. dashshft = dashSize * shft / (dashSize + gapSize);
  30633. for (i = 0; i < points.length - 1; i++) {
  30634. points[i + 1].subtractToRef(points[i], curvect);
  30635. nb = Math.floor(curvect.length() / shft);
  30636. curvect.normalize();
  30637. for (var j = 0; j < nb; j++) {
  30638. curshft = shft * j;
  30639. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30640. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30641. indices.push(idx, idx + 1);
  30642. idx += 2;
  30643. }
  30644. }
  30645. // Result
  30646. var vertexData = new VertexData();
  30647. vertexData.positions = positions;
  30648. vertexData.indices = indices;
  30649. return vertexData;
  30650. };
  30651. /**
  30652. * Creates the VertexData of the Ground.
  30653. */
  30654. VertexData.CreateGround = function (options) {
  30655. var indices = [];
  30656. var positions = [];
  30657. var normals = [];
  30658. var uvs = [];
  30659. var row, col;
  30660. var width = options.width || 1;
  30661. var height = options.height || 1;
  30662. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30663. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30664. for (row = 0; row <= subdivisionsY; row++) {
  30665. for (col = 0; col <= subdivisionsX; col++) {
  30666. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30667. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30668. positions.push(position.x, position.y, position.z);
  30669. normals.push(normal.x, normal.y, normal.z);
  30670. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30671. }
  30672. }
  30673. for (row = 0; row < subdivisionsY; row++) {
  30674. for (col = 0; col < subdivisionsX; col++) {
  30675. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30676. indices.push(col + 1 + row * (subdivisionsX + 1));
  30677. indices.push(col + row * (subdivisionsX + 1));
  30678. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30679. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30680. indices.push(col + row * (subdivisionsX + 1));
  30681. }
  30682. }
  30683. // Result
  30684. var vertexData = new VertexData();
  30685. vertexData.indices = indices;
  30686. vertexData.positions = positions;
  30687. vertexData.normals = normals;
  30688. vertexData.uvs = uvs;
  30689. return vertexData;
  30690. };
  30691. /**
  30692. * Creates the VertexData of the TiledGround.
  30693. */
  30694. VertexData.CreateTiledGround = function (options) {
  30695. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30696. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30697. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30698. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30699. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30700. var precision = options.precision || { w: 1, h: 1 };
  30701. var indices = new Array();
  30702. var positions = new Array();
  30703. var normals = new Array();
  30704. var uvs = new Array();
  30705. var row, col, tileRow, tileCol;
  30706. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30707. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30708. precision.w = (precision.w < 1) ? 1 : precision.w;
  30709. precision.h = (precision.h < 1) ? 1 : precision.h;
  30710. var tileSize = {
  30711. 'w': (xmax - xmin) / subdivisions.w,
  30712. 'h': (zmax - zmin) / subdivisions.h
  30713. };
  30714. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30715. // Indices
  30716. var base = positions.length / 3;
  30717. var rowLength = precision.w + 1;
  30718. for (row = 0; row < precision.h; row++) {
  30719. for (col = 0; col < precision.w; col++) {
  30720. var square = [
  30721. base + col + row * rowLength,
  30722. base + (col + 1) + row * rowLength,
  30723. base + (col + 1) + (row + 1) * rowLength,
  30724. base + col + (row + 1) * rowLength
  30725. ];
  30726. indices.push(square[1]);
  30727. indices.push(square[2]);
  30728. indices.push(square[3]);
  30729. indices.push(square[0]);
  30730. indices.push(square[1]);
  30731. indices.push(square[3]);
  30732. }
  30733. }
  30734. // Position, normals and uvs
  30735. var position = BABYLON.Vector3.Zero();
  30736. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30737. for (row = 0; row <= precision.h; row++) {
  30738. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30739. for (col = 0; col <= precision.w; col++) {
  30740. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30741. position.y = 0;
  30742. positions.push(position.x, position.y, position.z);
  30743. normals.push(normal.x, normal.y, normal.z);
  30744. uvs.push(col / precision.w, row / precision.h);
  30745. }
  30746. }
  30747. }
  30748. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30749. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30750. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30751. }
  30752. }
  30753. // Result
  30754. var vertexData = new VertexData();
  30755. vertexData.indices = indices;
  30756. vertexData.positions = positions;
  30757. vertexData.normals = normals;
  30758. vertexData.uvs = uvs;
  30759. return vertexData;
  30760. };
  30761. /**
  30762. * Creates the VertexData of the Ground designed from a heightmap.
  30763. */
  30764. VertexData.CreateGroundFromHeightMap = function (options) {
  30765. var indices = [];
  30766. var positions = [];
  30767. var normals = [];
  30768. var uvs = [];
  30769. var row, col;
  30770. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30771. // Vertices
  30772. for (row = 0; row <= options.subdivisions; row++) {
  30773. for (col = 0; col <= options.subdivisions; col++) {
  30774. 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));
  30775. // Compute height
  30776. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30777. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30778. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30779. var r = options.buffer[pos] / 255.0;
  30780. var g = options.buffer[pos + 1] / 255.0;
  30781. var b = options.buffer[pos + 2] / 255.0;
  30782. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30783. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30784. // Add vertex
  30785. positions.push(position.x, position.y, position.z);
  30786. normals.push(0, 0, 0);
  30787. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30788. }
  30789. }
  30790. // Indices
  30791. for (row = 0; row < options.subdivisions; row++) {
  30792. for (col = 0; col < options.subdivisions; col++) {
  30793. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30794. indices.push(col + 1 + row * (options.subdivisions + 1));
  30795. indices.push(col + row * (options.subdivisions + 1));
  30796. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30797. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30798. indices.push(col + row * (options.subdivisions + 1));
  30799. }
  30800. }
  30801. // Normals
  30802. VertexData.ComputeNormals(positions, indices, normals);
  30803. // Result
  30804. var vertexData = new VertexData();
  30805. vertexData.indices = indices;
  30806. vertexData.positions = positions;
  30807. vertexData.normals = normals;
  30808. vertexData.uvs = uvs;
  30809. return vertexData;
  30810. };
  30811. /**
  30812. * Creates the VertexData of the Plane.
  30813. */
  30814. VertexData.CreatePlane = function (options) {
  30815. var indices = [];
  30816. var positions = [];
  30817. var normals = [];
  30818. var uvs = [];
  30819. var width = options.width || options.size || 1;
  30820. var height = options.height || options.size || 1;
  30821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30822. // Vertices
  30823. var halfWidth = width / 2.0;
  30824. var halfHeight = height / 2.0;
  30825. positions.push(-halfWidth, -halfHeight, 0);
  30826. normals.push(0, 0, -1.0);
  30827. uvs.push(0.0, 0.0);
  30828. positions.push(halfWidth, -halfHeight, 0);
  30829. normals.push(0, 0, -1.0);
  30830. uvs.push(1.0, 0.0);
  30831. positions.push(halfWidth, halfHeight, 0);
  30832. normals.push(0, 0, -1.0);
  30833. uvs.push(1.0, 1.0);
  30834. positions.push(-halfWidth, halfHeight, 0);
  30835. normals.push(0, 0, -1.0);
  30836. uvs.push(0.0, 1.0);
  30837. // Indices
  30838. indices.push(0);
  30839. indices.push(1);
  30840. indices.push(2);
  30841. indices.push(0);
  30842. indices.push(2);
  30843. indices.push(3);
  30844. // Sides
  30845. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30846. // Result
  30847. var vertexData = new VertexData();
  30848. vertexData.indices = indices;
  30849. vertexData.positions = positions;
  30850. vertexData.normals = normals;
  30851. vertexData.uvs = uvs;
  30852. return vertexData;
  30853. };
  30854. /**
  30855. * Creates the VertexData of the Disc or regular Polygon.
  30856. */
  30857. VertexData.CreateDisc = function (options) {
  30858. var positions = new Array();
  30859. var indices = new Array();
  30860. var normals = new Array();
  30861. var uvs = new Array();
  30862. var radius = options.radius || 0.5;
  30863. var tessellation = options.tessellation || 64;
  30864. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30865. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30866. // positions and uvs
  30867. positions.push(0, 0, 0); // disc center first
  30868. uvs.push(0.5, 0.5);
  30869. var theta = Math.PI * 2 * arc;
  30870. var step = theta / tessellation;
  30871. for (var a = 0; a < theta; a += step) {
  30872. var x = Math.cos(a);
  30873. var y = Math.sin(a);
  30874. var u = (x + 1) / 2;
  30875. var v = (1 - y) / 2;
  30876. positions.push(radius * x, radius * y, 0);
  30877. uvs.push(u, v);
  30878. }
  30879. if (arc === 1) {
  30880. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30881. uvs.push(uvs[2], uvs[3]);
  30882. }
  30883. //indices
  30884. var vertexNb = positions.length / 3;
  30885. for (var i = 1; i < vertexNb - 1; i++) {
  30886. indices.push(i + 1, 0, i);
  30887. }
  30888. // result
  30889. VertexData.ComputeNormals(positions, indices, normals);
  30890. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30891. var vertexData = new VertexData();
  30892. vertexData.indices = indices;
  30893. vertexData.positions = positions;
  30894. vertexData.normals = normals;
  30895. vertexData.uvs = uvs;
  30896. return vertexData;
  30897. };
  30898. /**
  30899. * Re-creates the VertexData of the Polygon for sideOrientation.
  30900. */
  30901. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30902. var faceUV = fUV || new Array(3);
  30903. var faceColors = fColors;
  30904. var colors = [];
  30905. // default face colors and UV if undefined
  30906. for (var f = 0; f < 3; f++) {
  30907. if (faceUV[f] === undefined) {
  30908. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30909. }
  30910. if (faceColors && faceColors[f] === undefined) {
  30911. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30912. }
  30913. }
  30914. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30915. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30916. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30917. var indices = polygon.getIndices();
  30918. // set face colours and textures
  30919. var idx = 0;
  30920. var face = 0;
  30921. for (var index = 0; index < normals.length; index += 3) {
  30922. //Edge Face no. 1
  30923. if (Math.abs(normals[index + 1]) < 0.001) {
  30924. face = 1;
  30925. }
  30926. //Top Face no. 0
  30927. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30928. face = 0;
  30929. }
  30930. //Bottom Face no. 2
  30931. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30932. face = 2;
  30933. }
  30934. idx = index / 3;
  30935. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30936. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30937. if (faceColors) {
  30938. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30939. }
  30940. }
  30941. // sides
  30942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30943. // Result
  30944. var vertexData = new VertexData();
  30945. vertexData.indices = indices;
  30946. vertexData.positions = positions;
  30947. vertexData.normals = normals;
  30948. vertexData.uvs = uvs;
  30949. if (faceColors) {
  30950. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30951. vertexData.colors = totalColors;
  30952. }
  30953. return vertexData;
  30954. };
  30955. /**
  30956. * Creates the VertexData of the IcoSphere.
  30957. */
  30958. VertexData.CreateIcoSphere = function (options) {
  30959. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30960. var radius = options.radius || 1;
  30961. var flat = (options.flat === undefined) ? true : options.flat;
  30962. var subdivisions = options.subdivisions || 4;
  30963. var radiusX = options.radiusX || radius;
  30964. var radiusY = options.radiusY || radius;
  30965. var radiusZ = options.radiusZ || radius;
  30966. var t = (1 + Math.sqrt(5)) / 2;
  30967. // 12 vertex x,y,z
  30968. var ico_vertices = [
  30969. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30970. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30971. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30972. ];
  30973. // index of 3 vertex makes a face of icopshere
  30974. var ico_indices = [
  30975. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30976. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30977. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30978. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30979. ];
  30980. // vertex for uv have aliased position, not for UV
  30981. var vertices_unalias_id = [
  30982. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30983. // vertex alias
  30984. 0,
  30985. 2,
  30986. 3,
  30987. 3,
  30988. 3,
  30989. 4,
  30990. 7,
  30991. 8,
  30992. 9,
  30993. 9,
  30994. 10,
  30995. 11 // 23: B + 12
  30996. ];
  30997. // uv as integer step (not pixels !)
  30998. var ico_vertexuv = [
  30999. 5, 1, 3, 1, 6, 4, 0, 0,
  31000. 5, 3, 4, 2, 2, 2, 4, 0,
  31001. 2, 0, 1, 1, 6, 0, 6, 2,
  31002. // vertex alias (for same vertex on different faces)
  31003. 0, 4,
  31004. 3, 3,
  31005. 4, 4,
  31006. 3, 1,
  31007. 4, 2,
  31008. 4, 4,
  31009. 0, 2,
  31010. 1, 1,
  31011. 2, 2,
  31012. 3, 3,
  31013. 1, 3,
  31014. 2, 4 // 23: B + 12
  31015. ];
  31016. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31017. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31018. // First island of uv mapping
  31019. // v = 4h 3+ 2
  31020. // v = 3h 9+ 4
  31021. // v = 2h 9+ 5 B
  31022. // v = 1h 9 1 0
  31023. // v = 0h 3 8 7 A
  31024. // u = 0 1 2 3 4 5 6 *a
  31025. // Second island of uv mapping
  31026. // v = 4h 0+ B+ 4+
  31027. // v = 3h A+ 2+
  31028. // v = 2h 7+ 6 3+
  31029. // v = 1h 8+ 3+
  31030. // v = 0h
  31031. // u = 0 1 2 3 4 5 6 *a
  31032. // Face layout on texture UV mapping
  31033. // ============
  31034. // \ 4 /\ 16 / ======
  31035. // \ / \ / /\ 11 /
  31036. // \/ 7 \/ / \ /
  31037. // ======= / 10 \/
  31038. // /\ 17 /\ =======
  31039. // / \ / \ \ 15 /\
  31040. // / 8 \/ 12 \ \ / \
  31041. // ============ \/ 6 \
  31042. // \ 18 /\ ============
  31043. // \ / \ \ 5 /\ 0 /
  31044. // \/ 13 \ \ / \ /
  31045. // ======= \/ 1 \/
  31046. // =============
  31047. // /\ 19 /\ 2 /\
  31048. // / \ / \ / \
  31049. // / 14 \/ 9 \/ 3 \
  31050. // ===================
  31051. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31052. var ustep = 138 / 1024;
  31053. var vstep = 239 / 1024;
  31054. var uoffset = 60 / 1024;
  31055. var voffset = 26 / 1024;
  31056. // Second island should have margin, not to touch the first island
  31057. // avoid any borderline artefact in pixel rounding
  31058. var island_u_offset = -40 / 1024;
  31059. var island_v_offset = +20 / 1024;
  31060. // face is either island 0 or 1 :
  31061. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31062. var island = [
  31063. 0, 0, 0, 0, 1,
  31064. 0, 0, 1, 1, 0,
  31065. 0, 0, 1, 1, 0,
  31066. 0, 1, 1, 1, 0 // 15 - 19
  31067. ];
  31068. var indices = new Array();
  31069. var positions = new Array();
  31070. var normals = new Array();
  31071. var uvs = new Array();
  31072. var current_indice = 0;
  31073. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31074. var face_vertex_pos = new Array(3);
  31075. var face_vertex_uv = new Array(3);
  31076. var v012;
  31077. for (v012 = 0; v012 < 3; v012++) {
  31078. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31079. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31080. }
  31081. // create all with normals
  31082. for (var face = 0; face < 20; face++) {
  31083. // 3 vertex per face
  31084. for (v012 = 0; v012 < 3; v012++) {
  31085. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31086. var v_id = ico_indices[3 * face + v012];
  31087. // vertex have 3D position (x,y,z)
  31088. 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]);
  31089. // Normalize to get normal, then scale to radius
  31090. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31091. // uv Coordinates from vertex ID
  31092. 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);
  31093. }
  31094. // Subdivide the face (interpolate pos, norm, uv)
  31095. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31096. // - norm is linear interpolation of vertex corner normal
  31097. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31098. // - uv is linear interpolation
  31099. //
  31100. // Topology is as below for sub-divide by 2
  31101. // vertex shown as v0,v1,v2
  31102. // interp index is i1 to progress in range [v0,v1[
  31103. // interp index is i2 to progress in range [v0,v2[
  31104. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31105. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31106. //
  31107. //
  31108. // i2 v2
  31109. // ^ ^
  31110. // / / \
  31111. // / / \
  31112. // / / \
  31113. // / / (0,1) \
  31114. // / #---------\
  31115. // / / \ (0,0)'/ \
  31116. // / / \ / \
  31117. // / / \ / \
  31118. // / / (0,0) \ / (1,0) \
  31119. // / #---------#---------\
  31120. // v0 v1
  31121. //
  31122. // --------------------> i1
  31123. //
  31124. // interp of (i1,i2):
  31125. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31126. // along i1 : lerp(x0,x1, i1/(S-i2))
  31127. //
  31128. // centroid of triangle is needed to get help normal computation
  31129. // (c1,c2) are used for centroid location
  31130. var interp_vertex = function (i1, i2, c1, c2) {
  31131. // vertex is interpolated from
  31132. // - face_vertex_pos[0..2]
  31133. // - face_vertex_uv[0..2]
  31134. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31135. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31136. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31137. pos_interp.normalize();
  31138. var vertex_normal;
  31139. if (flat) {
  31140. // in flat mode, recalculate normal as face centroid normal
  31141. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31142. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31143. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31144. }
  31145. else {
  31146. // in smooth mode, recalculate normal from each single vertex position
  31147. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31148. }
  31149. // Vertex normal need correction due to X,Y,Z radius scaling
  31150. vertex_normal.x /= radiusX;
  31151. vertex_normal.y /= radiusY;
  31152. vertex_normal.z /= radiusZ;
  31153. vertex_normal.normalize();
  31154. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31155. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31156. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31157. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31158. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31159. uvs.push(uv_interp.x, uv_interp.y);
  31160. // push each vertex has member of a face
  31161. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31162. indices.push(current_indice);
  31163. current_indice++;
  31164. };
  31165. for (var i2 = 0; i2 < subdivisions; i2++) {
  31166. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31167. // face : (i1,i2) for /\ :
  31168. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31169. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31170. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31171. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31172. if (i1 + i2 + 1 < subdivisions) {
  31173. // face : (i1,i2)' for \/ :
  31174. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31175. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31176. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31177. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31178. }
  31179. }
  31180. }
  31181. }
  31182. // Sides
  31183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31184. // Result
  31185. var vertexData = new VertexData();
  31186. vertexData.indices = indices;
  31187. vertexData.positions = positions;
  31188. vertexData.normals = normals;
  31189. vertexData.uvs = uvs;
  31190. return vertexData;
  31191. };
  31192. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31193. /**
  31194. * Creates the VertexData of the Polyhedron.
  31195. */
  31196. VertexData.CreatePolyhedron = function (options) {
  31197. // provided polyhedron types :
  31198. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31199. // 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)
  31200. var polyhedra = [];
  31201. 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]] };
  31202. 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]] };
  31203. polyhedra[2] = {
  31204. 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]],
  31205. 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]]
  31206. };
  31207. polyhedra[3] = {
  31208. 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]],
  31209. 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]]
  31210. };
  31211. polyhedra[4] = {
  31212. 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]],
  31213. 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]]
  31214. };
  31215. 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]] };
  31216. 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]] };
  31217. 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]] };
  31218. 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]] };
  31219. 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]] };
  31220. 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]] };
  31221. 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]] };
  31222. 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]] };
  31223. 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]] };
  31224. polyhedra[14] = {
  31225. 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]],
  31226. 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]]
  31227. };
  31228. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31229. var size = options.size;
  31230. var sizeX = options.sizeX || size || 1;
  31231. var sizeY = options.sizeY || size || 1;
  31232. var sizeZ = options.sizeZ || size || 1;
  31233. var data = options.custom || polyhedra[type];
  31234. var nbfaces = data.face.length;
  31235. var faceUV = options.faceUV || new Array(nbfaces);
  31236. var faceColors = options.faceColors;
  31237. var flat = (options.flat === undefined) ? true : options.flat;
  31238. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31239. var positions = new Array();
  31240. var indices = new Array();
  31241. var normals = new Array();
  31242. var uvs = new Array();
  31243. var colors = new Array();
  31244. var index = 0;
  31245. var faceIdx = 0; // face cursor in the array "indexes"
  31246. var indexes = new Array();
  31247. var i = 0;
  31248. var f = 0;
  31249. var u, v, ang, x, y, tmp;
  31250. // default face colors and UV if undefined
  31251. if (flat) {
  31252. for (f = 0; f < nbfaces; f++) {
  31253. if (faceColors && faceColors[f] === undefined) {
  31254. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31255. }
  31256. if (faceUV && faceUV[f] === undefined) {
  31257. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31258. }
  31259. }
  31260. }
  31261. if (!flat) {
  31262. for (i = 0; i < data.vertex.length; i++) {
  31263. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31264. uvs.push(0, 0);
  31265. }
  31266. for (f = 0; f < nbfaces; f++) {
  31267. for (i = 0; i < data.face[f].length - 2; i++) {
  31268. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31269. }
  31270. }
  31271. }
  31272. else {
  31273. for (f = 0; f < nbfaces; f++) {
  31274. var fl = data.face[f].length; // number of vertices of the current face
  31275. ang = 2 * Math.PI / fl;
  31276. x = 0.5 * Math.tan(ang / 2);
  31277. y = 0.5;
  31278. // positions, uvs, colors
  31279. for (i = 0; i < fl; i++) {
  31280. // positions
  31281. 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);
  31282. indexes.push(index);
  31283. index++;
  31284. // uvs
  31285. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31286. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31287. uvs.push(u, v);
  31288. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31289. y = x * Math.sin(ang) + y * Math.cos(ang);
  31290. x = tmp;
  31291. // colors
  31292. if (faceColors) {
  31293. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31294. }
  31295. }
  31296. // indices from indexes
  31297. for (i = 0; i < fl - 2; i++) {
  31298. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31299. }
  31300. faceIdx += fl;
  31301. }
  31302. }
  31303. VertexData.ComputeNormals(positions, indices, normals);
  31304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31305. var vertexData = new VertexData();
  31306. vertexData.positions = positions;
  31307. vertexData.indices = indices;
  31308. vertexData.normals = normals;
  31309. vertexData.uvs = uvs;
  31310. if (faceColors && flat) {
  31311. vertexData.colors = colors;
  31312. }
  31313. return vertexData;
  31314. };
  31315. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31316. /**
  31317. * Creates the VertexData of the Torus Knot.
  31318. */
  31319. VertexData.CreateTorusKnot = function (options) {
  31320. var indices = new Array();
  31321. var positions = new Array();
  31322. var normals = new Array();
  31323. var uvs = new Array();
  31324. var radius = options.radius || 2;
  31325. var tube = options.tube || 0.5;
  31326. var radialSegments = options.radialSegments || 32;
  31327. var tubularSegments = options.tubularSegments || 32;
  31328. var p = options.p || 2;
  31329. var q = options.q || 3;
  31330. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31331. // Helper
  31332. var getPos = function (angle) {
  31333. var cu = Math.cos(angle);
  31334. var su = Math.sin(angle);
  31335. var quOverP = q / p * angle;
  31336. var cs = Math.cos(quOverP);
  31337. var tx = radius * (2 + cs) * 0.5 * cu;
  31338. var ty = radius * (2 + cs) * su * 0.5;
  31339. var tz = radius * Math.sin(quOverP) * 0.5;
  31340. return new BABYLON.Vector3(tx, ty, tz);
  31341. };
  31342. // Vertices
  31343. var i;
  31344. var j;
  31345. for (i = 0; i <= radialSegments; i++) {
  31346. var modI = i % radialSegments;
  31347. var u = modI / radialSegments * 2 * p * Math.PI;
  31348. var p1 = getPos(u);
  31349. var p2 = getPos(u + 0.01);
  31350. var tang = p2.subtract(p1);
  31351. var n = p2.add(p1);
  31352. var bitan = BABYLON.Vector3.Cross(tang, n);
  31353. n = BABYLON.Vector3.Cross(bitan, tang);
  31354. bitan.normalize();
  31355. n.normalize();
  31356. for (j = 0; j < tubularSegments; j++) {
  31357. var modJ = j % tubularSegments;
  31358. var v = modJ / tubularSegments * 2 * Math.PI;
  31359. var cx = -tube * Math.cos(v);
  31360. var cy = tube * Math.sin(v);
  31361. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31362. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31363. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31364. uvs.push(i / radialSegments);
  31365. uvs.push(j / tubularSegments);
  31366. }
  31367. }
  31368. for (i = 0; i < radialSegments; i++) {
  31369. for (j = 0; j < tubularSegments; j++) {
  31370. var jNext = (j + 1) % tubularSegments;
  31371. var a = i * tubularSegments + j;
  31372. var b = (i + 1) * tubularSegments + j;
  31373. var c = (i + 1) * tubularSegments + jNext;
  31374. var d = i * tubularSegments + jNext;
  31375. indices.push(d);
  31376. indices.push(b);
  31377. indices.push(a);
  31378. indices.push(d);
  31379. indices.push(c);
  31380. indices.push(b);
  31381. }
  31382. }
  31383. // Normals
  31384. VertexData.ComputeNormals(positions, indices, normals);
  31385. // Sides
  31386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31387. // Result
  31388. var vertexData = new VertexData();
  31389. vertexData.indices = indices;
  31390. vertexData.positions = positions;
  31391. vertexData.normals = normals;
  31392. vertexData.uvs = uvs;
  31393. return vertexData;
  31394. };
  31395. // Tools
  31396. /**
  31397. * @param {any} - positions (number[] or Float32Array)
  31398. * @param {any} - indices (number[] or Uint16Array)
  31399. * @param {any} - normals (number[] or Float32Array)
  31400. * options (optional) :
  31401. * facetPositions : optional array of facet positions (vector3)
  31402. * facetNormals : optional array of facet normals (vector3)
  31403. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31404. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31405. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31406. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31407. * bInfo : optional bounding info, required for facetPartitioning computation
  31408. * useRightHandedSystem: optional boolean to for right handed system computation
  31409. * depthSort : optional boolean to enable the facet depth sort computation
  31410. * distanceTo : optional Vector3 to compute the facet depth from this location
  31411. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31412. */
  31413. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31414. // temporary scalar variables
  31415. var index = 0; // facet index
  31416. var p1p2x = 0.0; // p1p2 vector x coordinate
  31417. var p1p2y = 0.0; // p1p2 vector y coordinate
  31418. var p1p2z = 0.0; // p1p2 vector z coordinate
  31419. var p3p2x = 0.0; // p3p2 vector x coordinate
  31420. var p3p2y = 0.0; // p3p2 vector y coordinate
  31421. var p3p2z = 0.0; // p3p2 vector z coordinate
  31422. var faceNormalx = 0.0; // facet normal x coordinate
  31423. var faceNormaly = 0.0; // facet normal y coordinate
  31424. var faceNormalz = 0.0; // facet normal z coordinate
  31425. var length = 0.0; // facet normal length before normalization
  31426. var v1x = 0; // vector1 x index in the positions array
  31427. var v1y = 0; // vector1 y index in the positions array
  31428. var v1z = 0; // vector1 z index in the positions array
  31429. var v2x = 0; // vector2 x index in the positions array
  31430. var v2y = 0; // vector2 y index in the positions array
  31431. var v2z = 0; // vector2 z index in the positions array
  31432. var v3x = 0; // vector3 x index in the positions array
  31433. var v3y = 0; // vector3 y index in the positions array
  31434. var v3z = 0; // vector3 z index in the positions array
  31435. var computeFacetNormals = false;
  31436. var computeFacetPositions = false;
  31437. var computeFacetPartitioning = false;
  31438. var computeDepthSort = false;
  31439. var faceNormalSign = 1;
  31440. var ratio = 0;
  31441. var distanceTo = null;
  31442. if (options) {
  31443. computeFacetNormals = (options.facetNormals) ? true : false;
  31444. computeFacetPositions = (options.facetPositions) ? true : false;
  31445. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31446. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31447. ratio = options.ratio || 0;
  31448. computeDepthSort = (options.depthSort) ? true : false;
  31449. distanceTo = (options.distanceTo);
  31450. if (computeDepthSort) {
  31451. if (distanceTo === undefined) {
  31452. distanceTo = BABYLON.Vector3.Zero();
  31453. }
  31454. var depthSortedFacets = options.depthSortedFacets;
  31455. }
  31456. }
  31457. // facetPartitioning reinit if needed
  31458. var xSubRatio = 0;
  31459. var ySubRatio = 0;
  31460. var zSubRatio = 0;
  31461. var subSq = 0;
  31462. if (computeFacetPartitioning && options && options.bbSize) {
  31463. var ox = 0; // X partitioning index for facet position
  31464. var oy = 0; // Y partinioning index for facet position
  31465. var oz = 0; // Z partinioning index for facet position
  31466. var b1x = 0; // X partitioning index for facet v1 vertex
  31467. var b1y = 0; // Y partitioning index for facet v1 vertex
  31468. var b1z = 0; // z partitioning index for facet v1 vertex
  31469. var b2x = 0; // X partitioning index for facet v2 vertex
  31470. var b2y = 0; // Y partitioning index for facet v2 vertex
  31471. var b2z = 0; // Z partitioning index for facet v2 vertex
  31472. var b3x = 0; // X partitioning index for facet v3 vertex
  31473. var b3y = 0; // Y partitioning index for facet v3 vertex
  31474. var b3z = 0; // Z partitioning index for facet v3 vertex
  31475. var block_idx_o = 0; // facet barycenter block index
  31476. var block_idx_v1 = 0; // v1 vertex block index
  31477. var block_idx_v2 = 0; // v2 vertex block index
  31478. var block_idx_v3 = 0; // v3 vertex block index
  31479. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31480. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31481. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31482. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31483. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31484. subSq = options.subDiv.max * options.subDiv.max;
  31485. options.facetPartitioning.length = 0;
  31486. }
  31487. // reset the normals
  31488. for (index = 0; index < positions.length; index++) {
  31489. normals[index] = 0.0;
  31490. }
  31491. // Loop : 1 indice triplet = 1 facet
  31492. var nbFaces = (indices.length / 3) | 0;
  31493. for (index = 0; index < nbFaces; index++) {
  31494. // get the indexes of the coordinates of each vertex of the facet
  31495. v1x = indices[index * 3] * 3;
  31496. v1y = v1x + 1;
  31497. v1z = v1x + 2;
  31498. v2x = indices[index * 3 + 1] * 3;
  31499. v2y = v2x + 1;
  31500. v2z = v2x + 2;
  31501. v3x = indices[index * 3 + 2] * 3;
  31502. v3y = v3x + 1;
  31503. v3z = v3x + 2;
  31504. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31505. p1p2y = positions[v1y] - positions[v2y];
  31506. p1p2z = positions[v1z] - positions[v2z];
  31507. p3p2x = positions[v3x] - positions[v2x];
  31508. p3p2y = positions[v3y] - positions[v2y];
  31509. p3p2z = positions[v3z] - positions[v2z];
  31510. // compute the face normal with the cross product
  31511. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31512. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31513. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31514. // normalize this normal and store it in the array facetData
  31515. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31516. length = (length === 0) ? 1.0 : length;
  31517. faceNormalx /= length;
  31518. faceNormaly /= length;
  31519. faceNormalz /= length;
  31520. if (computeFacetNormals && options) {
  31521. options.facetNormals[index].x = faceNormalx;
  31522. options.facetNormals[index].y = faceNormaly;
  31523. options.facetNormals[index].z = faceNormalz;
  31524. }
  31525. if (computeFacetPositions && options) {
  31526. // compute and the facet barycenter coordinates in the array facetPositions
  31527. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31528. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31529. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31530. }
  31531. if (computeFacetPartitioning && options) {
  31532. // store the facet indexes in arrays in the main facetPartitioning array :
  31533. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31534. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31535. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31536. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31537. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31538. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31539. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31540. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31541. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31542. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31543. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31544. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31545. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31546. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31547. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31548. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31549. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31550. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31551. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31552. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31553. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31554. // push each facet index in each block containing the vertex
  31555. options.facetPartitioning[block_idx_v1].push(index);
  31556. if (block_idx_v2 != block_idx_v1) {
  31557. options.facetPartitioning[block_idx_v2].push(index);
  31558. }
  31559. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31560. options.facetPartitioning[block_idx_v3].push(index);
  31561. }
  31562. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31563. options.facetPartitioning[block_idx_o].push(index);
  31564. }
  31565. }
  31566. if (computeDepthSort && options && options.facetPositions) {
  31567. var dsf = depthSortedFacets[index];
  31568. dsf.ind = index * 3;
  31569. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31570. }
  31571. // compute the normals anyway
  31572. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31573. normals[v1y] += faceNormaly;
  31574. normals[v1z] += faceNormalz;
  31575. normals[v2x] += faceNormalx;
  31576. normals[v2y] += faceNormaly;
  31577. normals[v2z] += faceNormalz;
  31578. normals[v3x] += faceNormalx;
  31579. normals[v3y] += faceNormaly;
  31580. normals[v3z] += faceNormalz;
  31581. }
  31582. // last normalization of each normal
  31583. for (index = 0; index < normals.length / 3; index++) {
  31584. faceNormalx = normals[index * 3];
  31585. faceNormaly = normals[index * 3 + 1];
  31586. faceNormalz = normals[index * 3 + 2];
  31587. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31588. length = (length === 0) ? 1.0 : length;
  31589. faceNormalx /= length;
  31590. faceNormaly /= length;
  31591. faceNormalz /= length;
  31592. normals[index * 3] = faceNormalx;
  31593. normals[index * 3 + 1] = faceNormaly;
  31594. normals[index * 3 + 2] = faceNormalz;
  31595. }
  31596. };
  31597. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31598. var li = indices.length;
  31599. var ln = normals.length;
  31600. var i;
  31601. var n;
  31602. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31603. switch (sideOrientation) {
  31604. case BABYLON.Mesh.FRONTSIDE:
  31605. // nothing changed
  31606. break;
  31607. case BABYLON.Mesh.BACKSIDE:
  31608. var tmp;
  31609. // indices
  31610. for (i = 0; i < li; i += 3) {
  31611. tmp = indices[i];
  31612. indices[i] = indices[i + 2];
  31613. indices[i + 2] = tmp;
  31614. }
  31615. // normals
  31616. for (n = 0; n < ln; n++) {
  31617. normals[n] = -normals[n];
  31618. }
  31619. break;
  31620. case BABYLON.Mesh.DOUBLESIDE:
  31621. // positions
  31622. var lp = positions.length;
  31623. var l = lp / 3;
  31624. for (var p = 0; p < lp; p++) {
  31625. positions[lp + p] = positions[p];
  31626. }
  31627. // indices
  31628. for (i = 0; i < li; i += 3) {
  31629. indices[i + li] = indices[i + 2] + l;
  31630. indices[i + 1 + li] = indices[i + 1] + l;
  31631. indices[i + 2 + li] = indices[i] + l;
  31632. }
  31633. // normals
  31634. for (n = 0; n < ln; n++) {
  31635. normals[ln + n] = -normals[n];
  31636. }
  31637. // uvs
  31638. var lu = uvs.length;
  31639. var u = 0;
  31640. for (u = 0; u < lu; u++) {
  31641. uvs[u + lu] = uvs[u];
  31642. }
  31643. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31644. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31645. u = 0;
  31646. for (i = 0; i < lu / 2; i++) {
  31647. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31648. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31649. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31650. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31651. u += 2;
  31652. }
  31653. break;
  31654. }
  31655. };
  31656. /**
  31657. * Creates a new VertexData from the imported parameters.
  31658. */
  31659. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31660. var vertexData = new VertexData();
  31661. // positions
  31662. var positions = parsedVertexData.positions;
  31663. if (positions) {
  31664. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31665. }
  31666. // normals
  31667. var normals = parsedVertexData.normals;
  31668. if (normals) {
  31669. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31670. }
  31671. // tangents
  31672. var tangents = parsedVertexData.tangents;
  31673. if (tangents) {
  31674. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31675. }
  31676. // uvs
  31677. var uvs = parsedVertexData.uvs;
  31678. if (uvs) {
  31679. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31680. }
  31681. // uv2s
  31682. var uv2s = parsedVertexData.uv2s;
  31683. if (uv2s) {
  31684. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31685. }
  31686. // uv3s
  31687. var uv3s = parsedVertexData.uv3s;
  31688. if (uv3s) {
  31689. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31690. }
  31691. // uv4s
  31692. var uv4s = parsedVertexData.uv4s;
  31693. if (uv4s) {
  31694. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31695. }
  31696. // uv5s
  31697. var uv5s = parsedVertexData.uv5s;
  31698. if (uv5s) {
  31699. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31700. }
  31701. // uv6s
  31702. var uv6s = parsedVertexData.uv6s;
  31703. if (uv6s) {
  31704. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31705. }
  31706. // colors
  31707. var colors = parsedVertexData.colors;
  31708. if (colors) {
  31709. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31710. }
  31711. // matricesIndices
  31712. var matricesIndices = parsedVertexData.matricesIndices;
  31713. if (matricesIndices) {
  31714. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31715. }
  31716. // matricesWeights
  31717. var matricesWeights = parsedVertexData.matricesWeights;
  31718. if (matricesWeights) {
  31719. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31720. }
  31721. // indices
  31722. var indices = parsedVertexData.indices;
  31723. if (indices) {
  31724. vertexData.indices = indices;
  31725. }
  31726. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31727. };
  31728. return VertexData;
  31729. }());
  31730. BABYLON.VertexData = VertexData;
  31731. })(BABYLON || (BABYLON = {}));
  31732. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31733. var BABYLON;
  31734. (function (BABYLON) {
  31735. /**
  31736. * Class used to store geometry data (vertex buffers + index buffer)
  31737. */
  31738. var Geometry = /** @class */ (function () {
  31739. /**
  31740. * Creates a new geometry
  31741. * @param id defines the unique ID
  31742. * @param scene defines the hosting scene
  31743. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  31744. * @param updatable defines if geometry must be updatable (false by default)
  31745. * @param mesh defines the mesh that will be associated with the geometry
  31746. */
  31747. function Geometry(id, scene, vertexData, updatable, mesh) {
  31748. if (updatable === void 0) { updatable = false; }
  31749. if (mesh === void 0) { mesh = null; }
  31750. /**
  31751. * Gets the delay loading state of the geometry (none by default which means not delayed)
  31752. */
  31753. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31754. this._totalVertices = 0;
  31755. this._isDisposed = false;
  31756. this._indexBufferIsUpdatable = false;
  31757. this.id = id;
  31758. this._engine = scene.getEngine();
  31759. this._meshes = [];
  31760. this._scene = scene;
  31761. //Init vertex buffer cache
  31762. this._vertexBuffers = {};
  31763. this._indices = [];
  31764. this._updatable = updatable;
  31765. // vertexData
  31766. if (vertexData) {
  31767. this.setAllVerticesData(vertexData, updatable);
  31768. }
  31769. else {
  31770. this._totalVertices = 0;
  31771. this._indices = [];
  31772. }
  31773. if (this._engine.getCaps().vertexArrayObject) {
  31774. this._vertexArrayObjects = {};
  31775. }
  31776. // applyToMesh
  31777. if (mesh) {
  31778. if (mesh.getClassName() === "LinesMesh") {
  31779. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31780. this.updateExtend();
  31781. }
  31782. this.applyToMesh(mesh);
  31783. mesh.computeWorldMatrix(true);
  31784. }
  31785. }
  31786. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31787. /**
  31788. * 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
  31789. */
  31790. get: function () {
  31791. return this._boundingBias;
  31792. },
  31793. /**
  31794. * 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
  31795. */
  31796. set: function (value) {
  31797. if (this._boundingBias && this._boundingBias.equals(value)) {
  31798. return;
  31799. }
  31800. this._boundingBias = value.clone();
  31801. this.updateBoundingInfo(true, null);
  31802. },
  31803. enumerable: true,
  31804. configurable: true
  31805. });
  31806. /**
  31807. * Static function used to attach a new empty geometry to a mesh
  31808. * @param mesh defines the mesh to attach the geometry to
  31809. * @returns the new {BABYLON.Geometry}
  31810. */
  31811. Geometry.CreateGeometryForMesh = function (mesh) {
  31812. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31813. geometry.applyToMesh(mesh);
  31814. return geometry;
  31815. };
  31816. Object.defineProperty(Geometry.prototype, "extend", {
  31817. /**
  31818. * Gets the current extend of the geometry
  31819. */
  31820. get: function () {
  31821. return this._extend;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. /**
  31827. * Gets the hosting scene
  31828. * @returns the hosting {BABYLON.Scene}
  31829. */
  31830. Geometry.prototype.getScene = function () {
  31831. return this._scene;
  31832. };
  31833. /**
  31834. * Gets the hosting engine
  31835. * @returns the hosting {BABYLON.Engine}
  31836. */
  31837. Geometry.prototype.getEngine = function () {
  31838. return this._engine;
  31839. };
  31840. /**
  31841. * Defines if the geometry is ready to use
  31842. * @returns true if the geometry is ready to be used
  31843. */
  31844. Geometry.prototype.isReady = function () {
  31845. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31846. };
  31847. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31848. /**
  31849. * Gets a value indicating that the geometry should not be serialized
  31850. */
  31851. get: function () {
  31852. for (var index = 0; index < this._meshes.length; index++) {
  31853. if (!this._meshes[index].doNotSerialize) {
  31854. return false;
  31855. }
  31856. }
  31857. return true;
  31858. },
  31859. enumerable: true,
  31860. configurable: true
  31861. });
  31862. /** @ignore */
  31863. Geometry.prototype._rebuild = function () {
  31864. if (this._vertexArrayObjects) {
  31865. this._vertexArrayObjects = {};
  31866. }
  31867. // Index buffer
  31868. if (this._meshes.length !== 0 && this._indices) {
  31869. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31870. }
  31871. // Vertex buffers
  31872. for (var key in this._vertexBuffers) {
  31873. var vertexBuffer = this._vertexBuffers[key];
  31874. vertexBuffer._rebuild();
  31875. }
  31876. };
  31877. /**
  31878. * Affects all gemetry data in one call
  31879. * @param vertexData defines the geometry data
  31880. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  31881. */
  31882. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31883. vertexData.applyToGeometry(this, updatable);
  31884. this.notifyUpdate();
  31885. };
  31886. /**
  31887. * Set specific vertex data
  31888. * @param kind defines the data kind (Position, normal, etc...)
  31889. * @param data defines the vertex data to use
  31890. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  31891. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  31892. */
  31893. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31894. if (updatable === void 0) { updatable = false; }
  31895. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31896. this.setVerticesBuffer(buffer);
  31897. };
  31898. /**
  31899. * Removes a specific vertex data
  31900. * @param kind defines the data kind (Position, normal, etc...)
  31901. */
  31902. Geometry.prototype.removeVerticesData = function (kind) {
  31903. if (this._vertexBuffers[kind]) {
  31904. this._vertexBuffers[kind].dispose();
  31905. delete this._vertexBuffers[kind];
  31906. }
  31907. };
  31908. /**
  31909. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  31910. * @param buffer defines the vertex buffer to use
  31911. */
  31912. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31913. var kind = buffer.getKind();
  31914. if (this._vertexBuffers[kind]) {
  31915. this._vertexBuffers[kind].dispose();
  31916. }
  31917. this._vertexBuffers[kind] = buffer;
  31918. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31919. var data = buffer.getData();
  31920. var stride = buffer.getStrideSize();
  31921. this._totalVertices = data.length / stride;
  31922. this.updateExtend(data, stride);
  31923. this._resetPointsArrayCache();
  31924. var meshes = this._meshes;
  31925. var numOfMeshes = meshes.length;
  31926. for (var index = 0; index < numOfMeshes; index++) {
  31927. var mesh = meshes[index];
  31928. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31929. mesh._createGlobalSubMesh(false);
  31930. mesh.computeWorldMatrix(true);
  31931. }
  31932. }
  31933. this.notifyUpdate(kind);
  31934. if (this._vertexArrayObjects) {
  31935. this._disposeVertexArrayObjects();
  31936. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31937. }
  31938. };
  31939. /**
  31940. * Update a specific vertex buffer
  31941. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  31942. * It will do nothing if the buffer is not updatable
  31943. * @param kind defines the data kind (Position, normal, etc...)
  31944. * @param data defines the data to use
  31945. * @param offset defines the offset in the target buffer where to store the data
  31946. */
  31947. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31948. var vertexBuffer = this.getVertexBuffer(kind);
  31949. if (!vertexBuffer) {
  31950. return;
  31951. }
  31952. vertexBuffer.updateDirectly(data, offset);
  31953. this.notifyUpdate(kind);
  31954. };
  31955. /**
  31956. * Update a specific vertex buffer
  31957. * This function will create a new buffer if the current one is not updatable
  31958. * @param kind defines the data kind (Position, normal, etc...)
  31959. * @param data defines the data to use
  31960. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  31961. */
  31962. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31963. if (updateExtends === void 0) { updateExtends = false; }
  31964. var vertexBuffer = this.getVertexBuffer(kind);
  31965. if (!vertexBuffer) {
  31966. return;
  31967. }
  31968. vertexBuffer.update(data);
  31969. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31970. var stride = vertexBuffer.getStrideSize();
  31971. this._totalVertices = data.length / stride;
  31972. this.updateBoundingInfo(updateExtends, data);
  31973. }
  31974. this.notifyUpdate(kind);
  31975. };
  31976. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31977. if (updateExtends) {
  31978. this.updateExtend(data);
  31979. }
  31980. var meshes = this._meshes;
  31981. var numOfMeshes = meshes.length;
  31982. this._resetPointsArrayCache();
  31983. for (var index = 0; index < numOfMeshes; index++) {
  31984. var mesh = meshes[index];
  31985. if (updateExtends) {
  31986. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31987. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31988. var subMesh = mesh.subMeshes[subIndex];
  31989. subMesh.refreshBoundingInfo();
  31990. }
  31991. }
  31992. }
  31993. };
  31994. /** @ignore */
  31995. Geometry.prototype._bind = function (effect, indexToBind) {
  31996. if (!effect) {
  31997. return;
  31998. }
  31999. if (indexToBind === undefined) {
  32000. indexToBind = this._indexBuffer;
  32001. }
  32002. var vbs = this.getVertexBuffers();
  32003. if (!vbs) {
  32004. return;
  32005. }
  32006. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32007. this._engine.bindBuffers(vbs, indexToBind, effect);
  32008. return;
  32009. }
  32010. // Using VAO
  32011. if (!this._vertexArrayObjects[effect.key]) {
  32012. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32013. }
  32014. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32015. };
  32016. /**
  32017. * Gets total number of vertices
  32018. * @returns the total number of vertices
  32019. */
  32020. Geometry.prototype.getTotalVertices = function () {
  32021. if (!this.isReady()) {
  32022. return 0;
  32023. }
  32024. return this._totalVertices;
  32025. };
  32026. /**
  32027. * Gets a specific vertex data attached to this geometry
  32028. * @param kind defines the data kind (Position, normal, etc...)
  32029. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32030. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32031. * @returns a float array containing vertex data
  32032. */
  32033. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32034. var vertexBuffer = this.getVertexBuffer(kind);
  32035. if (!vertexBuffer) {
  32036. return null;
  32037. }
  32038. var orig = vertexBuffer.getData();
  32039. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32040. return orig;
  32041. }
  32042. else {
  32043. var len = orig.length;
  32044. var copy = [];
  32045. for (var i = 0; i < len; i++) {
  32046. copy.push(orig[i]);
  32047. }
  32048. return copy;
  32049. }
  32050. };
  32051. /**
  32052. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32053. * @param kind defines the data kind (Position, normal, etc...)
  32054. * @returns true if the vertex buffer with the specified kind is updatable
  32055. */
  32056. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32057. var vb = this._vertexBuffers[kind];
  32058. if (!vb) {
  32059. return false;
  32060. }
  32061. return vb.isUpdatable();
  32062. };
  32063. /**
  32064. * Gets a specific vertex buffer
  32065. * @param kind defines the data kind (Position, normal, etc...)
  32066. * @returns a {BABYLON.VertexBuffer}
  32067. */
  32068. Geometry.prototype.getVertexBuffer = function (kind) {
  32069. if (!this.isReady()) {
  32070. return null;
  32071. }
  32072. return this._vertexBuffers[kind];
  32073. };
  32074. /**
  32075. * Returns all vertex buffers
  32076. * @return an object holding all vertex buffers indexed by kind
  32077. */
  32078. Geometry.prototype.getVertexBuffers = function () {
  32079. if (!this.isReady()) {
  32080. return null;
  32081. }
  32082. return this._vertexBuffers;
  32083. };
  32084. /**
  32085. * Gets a boolean indicating if specific vertex buffer is present
  32086. * @param kind defines the data kind (Position, normal, etc...)
  32087. * @returns true if data is present
  32088. */
  32089. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32090. if (!this._vertexBuffers) {
  32091. if (this._delayInfo) {
  32092. return this._delayInfo.indexOf(kind) !== -1;
  32093. }
  32094. return false;
  32095. }
  32096. return this._vertexBuffers[kind] !== undefined;
  32097. };
  32098. /**
  32099. * Gets a list of all attached data kinds (Position, normal, etc...)
  32100. * @returns a list of string containing all kinds
  32101. */
  32102. Geometry.prototype.getVerticesDataKinds = function () {
  32103. var result = [];
  32104. var kind;
  32105. if (!this._vertexBuffers && this._delayInfo) {
  32106. for (kind in this._delayInfo) {
  32107. result.push(kind);
  32108. }
  32109. }
  32110. else {
  32111. for (kind in this._vertexBuffers) {
  32112. result.push(kind);
  32113. }
  32114. }
  32115. return result;
  32116. };
  32117. /**
  32118. * Update index buffer
  32119. * @param indices defines the indices to store in the index buffer
  32120. * @param offset defines the offset in the target buffer where to store the data
  32121. */
  32122. Geometry.prototype.updateIndices = function (indices, offset) {
  32123. if (!this._indexBuffer) {
  32124. return;
  32125. }
  32126. if (!this._indexBufferIsUpdatable) {
  32127. this.setIndices(indices, null, true);
  32128. }
  32129. else {
  32130. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32131. }
  32132. };
  32133. /**
  32134. * Creates a new index buffer
  32135. * @param indices defines the indices to store in the index buffer
  32136. * @param totalVertices defines the total number of vertices (could be null)
  32137. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32138. */
  32139. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32140. if (totalVertices === void 0) { totalVertices = null; }
  32141. if (updatable === void 0) { updatable = false; }
  32142. if (this._indexBuffer) {
  32143. this._engine._releaseBuffer(this._indexBuffer);
  32144. }
  32145. this._disposeVertexArrayObjects();
  32146. this._indices = indices;
  32147. this._indexBufferIsUpdatable = updatable;
  32148. if (this._meshes.length !== 0 && this._indices) {
  32149. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32150. }
  32151. if (totalVertices != undefined) {
  32152. this._totalVertices = totalVertices;
  32153. }
  32154. var meshes = this._meshes;
  32155. var numOfMeshes = meshes.length;
  32156. for (var index = 0; index < numOfMeshes; index++) {
  32157. meshes[index]._createGlobalSubMesh(true);
  32158. }
  32159. this.notifyUpdate();
  32160. };
  32161. /**
  32162. * Return the total number of indices
  32163. * @returns the total number of indices
  32164. */
  32165. Geometry.prototype.getTotalIndices = function () {
  32166. if (!this.isReady()) {
  32167. return 0;
  32168. }
  32169. return this._indices.length;
  32170. };
  32171. /**
  32172. * Gets the index buffer array
  32173. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32174. * @returns the index buffer array
  32175. */
  32176. Geometry.prototype.getIndices = function (copyWhenShared) {
  32177. if (!this.isReady()) {
  32178. return null;
  32179. }
  32180. var orig = this._indices;
  32181. if (!copyWhenShared || this._meshes.length === 1) {
  32182. return orig;
  32183. }
  32184. else {
  32185. var len = orig.length;
  32186. var copy = [];
  32187. for (var i = 0; i < len; i++) {
  32188. copy.push(orig[i]);
  32189. }
  32190. return copy;
  32191. }
  32192. };
  32193. /**
  32194. * Gets the index buffer
  32195. * @return the index buffer
  32196. */
  32197. Geometry.prototype.getIndexBuffer = function () {
  32198. if (!this.isReady()) {
  32199. return null;
  32200. }
  32201. return this._indexBuffer;
  32202. };
  32203. /** @ignore */
  32204. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32205. if (effect === void 0) { effect = null; }
  32206. if (!effect || !this._vertexArrayObjects) {
  32207. return;
  32208. }
  32209. if (this._vertexArrayObjects[effect.key]) {
  32210. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32211. delete this._vertexArrayObjects[effect.key];
  32212. }
  32213. };
  32214. /**
  32215. * Release the associated resources for a specific mesh
  32216. * @param mesh defines the source mesh
  32217. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32218. */
  32219. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32220. var meshes = this._meshes;
  32221. var index = meshes.indexOf(mesh);
  32222. if (index === -1) {
  32223. return;
  32224. }
  32225. meshes.splice(index, 1);
  32226. mesh._geometry = null;
  32227. if (meshes.length === 0 && shouldDispose) {
  32228. this.dispose();
  32229. }
  32230. };
  32231. /**
  32232. * Apply current geometry to a given mesh
  32233. * @param mesh defines the mesh to apply geometry to
  32234. */
  32235. Geometry.prototype.applyToMesh = function (mesh) {
  32236. if (mesh._geometry === this) {
  32237. return;
  32238. }
  32239. var previousGeometry = mesh._geometry;
  32240. if (previousGeometry) {
  32241. previousGeometry.releaseForMesh(mesh);
  32242. }
  32243. var meshes = this._meshes;
  32244. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32245. mesh._geometry = this;
  32246. this._scene.pushGeometry(this);
  32247. meshes.push(mesh);
  32248. if (this.isReady()) {
  32249. this._applyToMesh(mesh);
  32250. }
  32251. else {
  32252. mesh._boundingInfo = this._boundingInfo;
  32253. }
  32254. };
  32255. Geometry.prototype.updateExtend = function (data, stride) {
  32256. if (data === void 0) { data = null; }
  32257. if (!data) {
  32258. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32259. }
  32260. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32261. };
  32262. Geometry.prototype._applyToMesh = function (mesh) {
  32263. var numOfMeshes = this._meshes.length;
  32264. // vertexBuffers
  32265. for (var kind in this._vertexBuffers) {
  32266. if (numOfMeshes === 1) {
  32267. this._vertexBuffers[kind].create();
  32268. }
  32269. var buffer = this._vertexBuffers[kind].getBuffer();
  32270. if (buffer)
  32271. buffer.references = numOfMeshes;
  32272. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32273. if (!this._extend) {
  32274. this.updateExtend(this._vertexBuffers[kind].getData());
  32275. }
  32276. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32277. mesh._createGlobalSubMesh(false);
  32278. //bounding info was just created again, world matrix should be applied again.
  32279. mesh._updateBoundingInfo();
  32280. }
  32281. }
  32282. // indexBuffer
  32283. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32284. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32285. }
  32286. if (this._indexBuffer) {
  32287. this._indexBuffer.references = numOfMeshes;
  32288. }
  32289. };
  32290. Geometry.prototype.notifyUpdate = function (kind) {
  32291. if (this.onGeometryUpdated) {
  32292. this.onGeometryUpdated(this, kind);
  32293. }
  32294. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32295. var mesh = _a[_i];
  32296. mesh._markSubMeshesAsAttributesDirty();
  32297. }
  32298. };
  32299. /**
  32300. * Load the geometry if it was flagged as delay loaded
  32301. * @param scene defines the hosting scene
  32302. * @param onLoaded defines a callback called when the geometry is loaded
  32303. */
  32304. Geometry.prototype.load = function (scene, onLoaded) {
  32305. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32306. return;
  32307. }
  32308. if (this.isReady()) {
  32309. if (onLoaded) {
  32310. onLoaded();
  32311. }
  32312. return;
  32313. }
  32314. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32315. this._queueLoad(scene, onLoaded);
  32316. };
  32317. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32318. var _this = this;
  32319. if (!this.delayLoadingFile) {
  32320. return;
  32321. }
  32322. scene._addPendingData(this);
  32323. scene._loadFile(this.delayLoadingFile, function (data) {
  32324. if (!_this._delayLoadingFunction) {
  32325. return;
  32326. }
  32327. _this._delayLoadingFunction(JSON.parse(data), _this);
  32328. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32329. _this._delayInfo = [];
  32330. scene._removePendingData(_this);
  32331. var meshes = _this._meshes;
  32332. var numOfMeshes = meshes.length;
  32333. for (var index = 0; index < numOfMeshes; index++) {
  32334. _this._applyToMesh(meshes[index]);
  32335. }
  32336. if (onLoaded) {
  32337. onLoaded();
  32338. }
  32339. }, undefined, true);
  32340. };
  32341. /**
  32342. * Invert the geometry to move from a right handed system to a left handed one.
  32343. */
  32344. Geometry.prototype.toLeftHanded = function () {
  32345. // Flip faces
  32346. var tIndices = this.getIndices(false);
  32347. if (tIndices != null && tIndices.length > 0) {
  32348. for (var i = 0; i < tIndices.length; i += 3) {
  32349. var tTemp = tIndices[i + 0];
  32350. tIndices[i + 0] = tIndices[i + 2];
  32351. tIndices[i + 2] = tTemp;
  32352. }
  32353. this.setIndices(tIndices);
  32354. }
  32355. // Negate position.z
  32356. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32357. if (tPositions != null && tPositions.length > 0) {
  32358. for (var i = 0; i < tPositions.length; i += 3) {
  32359. tPositions[i + 2] = -tPositions[i + 2];
  32360. }
  32361. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32362. }
  32363. // Negate normal.z
  32364. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32365. if (tNormals != null && tNormals.length > 0) {
  32366. for (var i = 0; i < tNormals.length; i += 3) {
  32367. tNormals[i + 2] = -tNormals[i + 2];
  32368. }
  32369. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32370. }
  32371. };
  32372. // Cache
  32373. /** @ignore */
  32374. Geometry.prototype._resetPointsArrayCache = function () {
  32375. this._positions = null;
  32376. };
  32377. /** @ignore */
  32378. Geometry.prototype._generatePointsArray = function () {
  32379. if (this._positions)
  32380. return true;
  32381. this._positions = [];
  32382. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32383. if (!data) {
  32384. return false;
  32385. }
  32386. for (var index = 0; index < data.length; index += 3) {
  32387. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32388. }
  32389. return true;
  32390. };
  32391. /**
  32392. * Gets a value indicating if the geometry is disposed
  32393. * @returns true if the geometry was disposed
  32394. */
  32395. Geometry.prototype.isDisposed = function () {
  32396. return this._isDisposed;
  32397. };
  32398. Geometry.prototype._disposeVertexArrayObjects = function () {
  32399. if (this._vertexArrayObjects) {
  32400. for (var kind in this._vertexArrayObjects) {
  32401. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32402. }
  32403. this._vertexArrayObjects = {};
  32404. }
  32405. };
  32406. /**
  32407. * Free all associated resources
  32408. */
  32409. Geometry.prototype.dispose = function () {
  32410. var meshes = this._meshes;
  32411. var numOfMeshes = meshes.length;
  32412. var index;
  32413. for (index = 0; index < numOfMeshes; index++) {
  32414. this.releaseForMesh(meshes[index]);
  32415. }
  32416. this._meshes = [];
  32417. this._disposeVertexArrayObjects();
  32418. for (var kind in this._vertexBuffers) {
  32419. this._vertexBuffers[kind].dispose();
  32420. }
  32421. this._vertexBuffers = {};
  32422. this._totalVertices = 0;
  32423. if (this._indexBuffer) {
  32424. this._engine._releaseBuffer(this._indexBuffer);
  32425. }
  32426. this._indexBuffer = null;
  32427. this._indices = [];
  32428. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32429. this.delayLoadingFile = null;
  32430. this._delayLoadingFunction = null;
  32431. this._delayInfo = [];
  32432. this._boundingInfo = null;
  32433. this._scene.removeGeometry(this);
  32434. this._isDisposed = true;
  32435. };
  32436. /**
  32437. * Clone the current geometry into a new geometry
  32438. * @param id defines the unique ID of the new geometry
  32439. * @returns a new geometry object
  32440. */
  32441. Geometry.prototype.copy = function (id) {
  32442. var vertexData = new BABYLON.VertexData();
  32443. vertexData.indices = [];
  32444. var indices = this.getIndices();
  32445. if (indices) {
  32446. for (var index = 0; index < indices.length; index++) {
  32447. vertexData.indices.push(indices[index]);
  32448. }
  32449. }
  32450. var updatable = false;
  32451. var stopChecking = false;
  32452. var kind;
  32453. for (kind in this._vertexBuffers) {
  32454. // using slice() to make a copy of the array and not just reference it
  32455. var data = this.getVerticesData(kind);
  32456. if (data instanceof Float32Array) {
  32457. vertexData.set(new Float32Array(data), kind);
  32458. }
  32459. else {
  32460. vertexData.set(data.slice(0), kind);
  32461. }
  32462. if (!stopChecking) {
  32463. var vb = this.getVertexBuffer(kind);
  32464. if (vb) {
  32465. updatable = vb.isUpdatable();
  32466. stopChecking = !updatable;
  32467. }
  32468. }
  32469. }
  32470. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32471. geometry.delayLoadState = this.delayLoadState;
  32472. geometry.delayLoadingFile = this.delayLoadingFile;
  32473. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32474. for (kind in this._delayInfo) {
  32475. geometry._delayInfo = geometry._delayInfo || [];
  32476. geometry._delayInfo.push(kind);
  32477. }
  32478. // Bounding info
  32479. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32480. return geometry;
  32481. };
  32482. /**
  32483. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32484. * @return a JSON representation of the current geometry data (without the vertices data)
  32485. */
  32486. Geometry.prototype.serialize = function () {
  32487. var serializationObject = {};
  32488. serializationObject.id = this.id;
  32489. serializationObject.updatable = this._updatable;
  32490. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32491. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32492. }
  32493. return serializationObject;
  32494. };
  32495. Geometry.prototype.toNumberArray = function (origin) {
  32496. if (Array.isArray(origin)) {
  32497. return origin;
  32498. }
  32499. else {
  32500. return Array.prototype.slice.call(origin);
  32501. }
  32502. };
  32503. /**
  32504. * Serialize all vertices data into a JSON oject
  32505. * @returns a JSON representation of the current geometry data
  32506. */
  32507. Geometry.prototype.serializeVerticeData = function () {
  32508. var serializationObject = this.serialize();
  32509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32510. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32512. serializationObject.positions._updatable = true;
  32513. }
  32514. }
  32515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32516. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32518. serializationObject.normals._updatable = true;
  32519. }
  32520. }
  32521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32522. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  32523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  32524. serializationObject.tangets._updatable = true;
  32525. }
  32526. }
  32527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32528. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32530. serializationObject.uvs._updatable = true;
  32531. }
  32532. }
  32533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32534. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32535. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32536. serializationObject.uv2s._updatable = true;
  32537. }
  32538. }
  32539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32540. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32541. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32542. serializationObject.uv3s._updatable = true;
  32543. }
  32544. }
  32545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32546. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32547. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32548. serializationObject.uv4s._updatable = true;
  32549. }
  32550. }
  32551. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32552. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32553. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32554. serializationObject.uv5s._updatable = true;
  32555. }
  32556. }
  32557. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32558. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32559. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32560. serializationObject.uv6s._updatable = true;
  32561. }
  32562. }
  32563. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32564. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32565. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32566. serializationObject.colors._updatable = true;
  32567. }
  32568. }
  32569. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32570. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32571. serializationObject.matricesIndices._isExpanded = true;
  32572. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32573. serializationObject.matricesIndices._updatable = true;
  32574. }
  32575. }
  32576. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32577. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32578. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32579. serializationObject.matricesWeights._updatable = true;
  32580. }
  32581. }
  32582. serializationObject.indices = this.toNumberArray(this.getIndices());
  32583. return serializationObject;
  32584. };
  32585. // Statics
  32586. /**
  32587. * Extracts a clone of a mesh geometry
  32588. * @param mesh defines the source mesh
  32589. * @param id defines the unique ID of the new geometry object
  32590. * @returns the new geometry object
  32591. */
  32592. Geometry.ExtractFromMesh = function (mesh, id) {
  32593. var geometry = mesh._geometry;
  32594. if (!geometry) {
  32595. return null;
  32596. }
  32597. return geometry.copy(id);
  32598. };
  32599. /**
  32600. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32601. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32602. * Be aware Math.random() could cause collisions, but:
  32603. * "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"
  32604. * @returns a string containing a new GUID
  32605. */
  32606. Geometry.RandomId = function () {
  32607. return BABYLON.Tools.RandomId();
  32608. };
  32609. /** @ignore */
  32610. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  32611. var scene = mesh.getScene();
  32612. // Geometry
  32613. var geometryId = parsedGeometry.geometryId;
  32614. if (geometryId) {
  32615. var geometry = scene.getGeometryByID(geometryId);
  32616. if (geometry) {
  32617. geometry.applyToMesh(mesh);
  32618. }
  32619. }
  32620. else if (parsedGeometry instanceof ArrayBuffer) {
  32621. var binaryInfo = mesh._binaryInfo;
  32622. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32623. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32624. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32625. }
  32626. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32627. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32628. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32629. }
  32630. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  32631. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  32632. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  32633. }
  32634. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32635. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32636. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32637. }
  32638. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32639. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32640. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32641. }
  32642. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32643. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32644. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32645. }
  32646. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32647. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32648. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32649. }
  32650. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32651. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32652. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32653. }
  32654. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32655. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32656. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32657. }
  32658. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32659. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32660. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32661. }
  32662. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32663. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32664. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32665. }
  32666. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32667. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32669. }
  32670. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32671. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32672. mesh.setIndices(indicesData, null);
  32673. }
  32674. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32675. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32676. mesh.subMeshes = [];
  32677. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32678. var materialIndex = subMeshesData[(i * 5) + 0];
  32679. var verticesStart = subMeshesData[(i * 5) + 1];
  32680. var verticesCount = subMeshesData[(i * 5) + 2];
  32681. var indexStart = subMeshesData[(i * 5) + 3];
  32682. var indexCount = subMeshesData[(i * 5) + 4];
  32683. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32684. }
  32685. }
  32686. }
  32687. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32688. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32690. if (parsedGeometry.tangents) {
  32691. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  32692. }
  32693. if (parsedGeometry.uvs) {
  32694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32695. }
  32696. if (parsedGeometry.uvs2) {
  32697. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32698. }
  32699. if (parsedGeometry.uvs3) {
  32700. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32701. }
  32702. if (parsedGeometry.uvs4) {
  32703. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32704. }
  32705. if (parsedGeometry.uvs5) {
  32706. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32707. }
  32708. if (parsedGeometry.uvs6) {
  32709. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32710. }
  32711. if (parsedGeometry.colors) {
  32712. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32713. }
  32714. if (parsedGeometry.matricesIndices) {
  32715. if (!parsedGeometry.matricesIndices._isExpanded) {
  32716. var floatIndices = [];
  32717. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32718. var matricesIndex = parsedGeometry.matricesIndices[i];
  32719. floatIndices.push(matricesIndex & 0x000000FF);
  32720. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32721. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32722. floatIndices.push(matricesIndex >> 24);
  32723. }
  32724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32725. }
  32726. else {
  32727. delete parsedGeometry.matricesIndices._isExpanded;
  32728. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32729. }
  32730. }
  32731. if (parsedGeometry.matricesIndicesExtra) {
  32732. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32733. var floatIndices = [];
  32734. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32735. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32736. floatIndices.push(matricesIndex & 0x000000FF);
  32737. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32738. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32739. floatIndices.push(matricesIndex >> 24);
  32740. }
  32741. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32742. }
  32743. else {
  32744. delete parsedGeometry.matricesIndices._isExpanded;
  32745. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32746. }
  32747. }
  32748. if (parsedGeometry.matricesWeights) {
  32749. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32750. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32751. }
  32752. if (parsedGeometry.matricesWeightsExtra) {
  32753. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32754. }
  32755. mesh.setIndices(parsedGeometry.indices, null);
  32756. }
  32757. // SubMeshes
  32758. if (parsedGeometry.subMeshes) {
  32759. mesh.subMeshes = [];
  32760. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32761. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32762. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32763. }
  32764. }
  32765. // Flat shading
  32766. if (mesh._shouldGenerateFlatShading) {
  32767. mesh.convertToFlatShadedMesh();
  32768. delete mesh._shouldGenerateFlatShading;
  32769. }
  32770. // Update
  32771. mesh.computeWorldMatrix(true);
  32772. // Octree
  32773. var sceneOctree = scene.selectionOctree;
  32774. if (sceneOctree !== undefined && sceneOctree !== null) {
  32775. sceneOctree.addMesh(mesh);
  32776. }
  32777. };
  32778. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32779. var epsilon = 1e-3;
  32780. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32781. return;
  32782. }
  32783. var noInfluenceBoneIndex = 0.0;
  32784. if (parsedGeometry.skeletonId > -1) {
  32785. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32786. if (!skeleton) {
  32787. return;
  32788. }
  32789. noInfluenceBoneIndex = skeleton.bones.length;
  32790. }
  32791. else {
  32792. return;
  32793. }
  32794. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32795. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32796. var matricesWeights = parsedGeometry.matricesWeights;
  32797. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32798. var influencers = parsedGeometry.numBoneInfluencer;
  32799. var size = matricesWeights.length;
  32800. for (var i = 0; i < size; i += 4) {
  32801. var weight = 0.0;
  32802. var firstZeroWeight = -1;
  32803. for (var j = 0; j < 4; j++) {
  32804. var w = matricesWeights[i + j];
  32805. weight += w;
  32806. if (w < epsilon && firstZeroWeight < 0) {
  32807. firstZeroWeight = j;
  32808. }
  32809. }
  32810. if (matricesWeightsExtra) {
  32811. for (var j = 0; j < 4; j++) {
  32812. var w = matricesWeightsExtra[i + j];
  32813. weight += w;
  32814. if (w < epsilon && firstZeroWeight < 0) {
  32815. firstZeroWeight = j + 4;
  32816. }
  32817. }
  32818. }
  32819. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32820. firstZeroWeight = influencers - 1;
  32821. }
  32822. if (weight > epsilon) {
  32823. var mweight = 1.0 / weight;
  32824. for (var j = 0; j < 4; j++) {
  32825. matricesWeights[i + j] *= mweight;
  32826. }
  32827. if (matricesWeightsExtra) {
  32828. for (var j = 0; j < 4; j++) {
  32829. matricesWeightsExtra[i + j] *= mweight;
  32830. }
  32831. }
  32832. }
  32833. else {
  32834. if (firstZeroWeight >= 4) {
  32835. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32836. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32837. }
  32838. else {
  32839. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32840. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32841. }
  32842. }
  32843. }
  32844. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32845. if (parsedGeometry.matricesWeightsExtra) {
  32846. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32847. }
  32848. };
  32849. /**
  32850. * Create a new geometry from persisted data (Using .babylon file format)
  32851. * @param parsedVertexData defines the persisted data
  32852. * @param scene defines the hosting scene
  32853. * @param rootUrl defines the root url to use to load assets (like delayed data)
  32854. * @returns the new geometry object
  32855. */
  32856. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32857. if (scene.getGeometryByID(parsedVertexData.id)) {
  32858. return null; // null since geometry could be something else than a box...
  32859. }
  32860. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32861. if (BABYLON.Tags) {
  32862. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32863. }
  32864. if (parsedVertexData.delayLoadingFile) {
  32865. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32866. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32867. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32868. geometry._delayInfo = [];
  32869. if (parsedVertexData.hasUVs) {
  32870. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32871. }
  32872. if (parsedVertexData.hasUVs2) {
  32873. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32874. }
  32875. if (parsedVertexData.hasUVs3) {
  32876. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32877. }
  32878. if (parsedVertexData.hasUVs4) {
  32879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32880. }
  32881. if (parsedVertexData.hasUVs5) {
  32882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32883. }
  32884. if (parsedVertexData.hasUVs6) {
  32885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32886. }
  32887. if (parsedVertexData.hasColors) {
  32888. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32889. }
  32890. if (parsedVertexData.hasMatricesIndices) {
  32891. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32892. }
  32893. if (parsedVertexData.hasMatricesWeights) {
  32894. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32895. }
  32896. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32897. }
  32898. else {
  32899. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32900. }
  32901. scene.pushGeometry(geometry, true);
  32902. return geometry;
  32903. };
  32904. return Geometry;
  32905. }());
  32906. BABYLON.Geometry = Geometry;
  32907. // Primitives
  32908. /// Abstract class
  32909. /**
  32910. * Abstract class used to provide common services for all typed geometries
  32911. */
  32912. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32913. __extends(_PrimitiveGeometry, _super);
  32914. /**
  32915. * Creates a new typed geometry
  32916. * @param id defines the unique ID of the geometry
  32917. * @param scene defines the hosting scene
  32918. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  32919. * @param mesh defines the hosting mesh (can be null)
  32920. */
  32921. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32922. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32923. if (mesh === void 0) { mesh = null; }
  32924. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32925. _this._canBeRegenerated = _canBeRegenerated;
  32926. _this._beingRegenerated = true;
  32927. _this.regenerate();
  32928. _this._beingRegenerated = false;
  32929. return _this;
  32930. }
  32931. /**
  32932. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  32933. * @returns true if the geometry can be regenerated
  32934. */
  32935. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32936. return this._canBeRegenerated;
  32937. };
  32938. /**
  32939. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  32940. */
  32941. _PrimitiveGeometry.prototype.regenerate = function () {
  32942. if (!this._canBeRegenerated) {
  32943. return;
  32944. }
  32945. this._beingRegenerated = true;
  32946. this.setAllVerticesData(this._regenerateVertexData(), false);
  32947. this._beingRegenerated = false;
  32948. };
  32949. /**
  32950. * Clone the geometry
  32951. * @param id defines the unique ID of the new geometry
  32952. * @returns the new geometry
  32953. */
  32954. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32955. return _super.prototype.copy.call(this, id);
  32956. };
  32957. // overrides
  32958. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32959. if (!this._beingRegenerated) {
  32960. return;
  32961. }
  32962. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32963. };
  32964. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32965. if (!this._beingRegenerated) {
  32966. return;
  32967. }
  32968. _super.prototype.setVerticesData.call(this, kind, data, false);
  32969. };
  32970. // to override
  32971. /** @ignore */
  32972. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32973. throw new Error("Abstract method");
  32974. };
  32975. _PrimitiveGeometry.prototype.copy = function (id) {
  32976. throw new Error("Must be overriden in sub-classes.");
  32977. };
  32978. _PrimitiveGeometry.prototype.serialize = function () {
  32979. var serializationObject = _super.prototype.serialize.call(this);
  32980. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32981. return serializationObject;
  32982. };
  32983. return _PrimitiveGeometry;
  32984. }(Geometry));
  32985. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32986. /**
  32987. * Creates a ribbon geometry
  32988. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  32989. */
  32990. var RibbonGeometry = /** @class */ (function (_super) {
  32991. __extends(RibbonGeometry, _super);
  32992. /**
  32993. * Creates a ribbon geometry
  32994. * @param id defines the unique ID of the geometry
  32995. * @param scene defines the hosting scene
  32996. * @param pathArray defines the array of paths to use
  32997. * @param closeArray defines if the last path and the first path must be joined
  32998. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  32999. * @param offset defines the offset between points
  33000. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33001. * @param mesh defines the hosting mesh (can be null)
  33002. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33003. */
  33004. function RibbonGeometry(id, scene,
  33005. /**
  33006. * Defines the array of paths to use
  33007. */
  33008. pathArray,
  33009. /**
  33010. * Defines if the last and first points of each path in your pathArray must be joined
  33011. */
  33012. closeArray,
  33013. /**
  33014. * Defines if the last and first points of each path in your pathArray must be joined
  33015. */
  33016. closePath,
  33017. /**
  33018. * Defines the offset between points
  33019. */
  33020. offset, canBeRegenerated, mesh,
  33021. /**
  33022. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33023. */
  33024. side) {
  33025. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33026. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33027. _this.pathArray = pathArray;
  33028. _this.closeArray = closeArray;
  33029. _this.closePath = closePath;
  33030. _this.offset = offset;
  33031. _this.side = side;
  33032. return _this;
  33033. }
  33034. /** @ignore */
  33035. RibbonGeometry.prototype._regenerateVertexData = function () {
  33036. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33037. };
  33038. RibbonGeometry.prototype.copy = function (id) {
  33039. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33040. };
  33041. return RibbonGeometry;
  33042. }(_PrimitiveGeometry));
  33043. BABYLON.RibbonGeometry = RibbonGeometry;
  33044. /**
  33045. * Creates a box geometry
  33046. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33047. */
  33048. var BoxGeometry = /** @class */ (function (_super) {
  33049. __extends(BoxGeometry, _super);
  33050. /**
  33051. * Creates a box geometry
  33052. * @param id defines the unique ID of the geometry
  33053. * @param scene defines the hosting scene
  33054. * @param size defines the zise of the box (width, height and depth are the same)
  33055. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33056. * @param mesh defines the hosting mesh (can be null)
  33057. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33058. */
  33059. function BoxGeometry(id, scene,
  33060. /**
  33061. * Defines the zise of the box (width, height and depth are the same)
  33062. */
  33063. size, canBeRegenerated, mesh,
  33064. /**
  33065. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33066. */
  33067. side) {
  33068. if (mesh === void 0) { mesh = null; }
  33069. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33070. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33071. _this.size = size;
  33072. _this.side = side;
  33073. return _this;
  33074. }
  33075. BoxGeometry.prototype._regenerateVertexData = function () {
  33076. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33077. };
  33078. BoxGeometry.prototype.copy = function (id) {
  33079. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33080. };
  33081. BoxGeometry.prototype.serialize = function () {
  33082. var serializationObject = _super.prototype.serialize.call(this);
  33083. serializationObject.size = this.size;
  33084. return serializationObject;
  33085. };
  33086. BoxGeometry.Parse = function (parsedBox, scene) {
  33087. if (scene.getGeometryByID(parsedBox.id)) {
  33088. return null; // null since geometry could be something else than a box...
  33089. }
  33090. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33091. if (BABYLON.Tags) {
  33092. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33093. }
  33094. scene.pushGeometry(box, true);
  33095. return box;
  33096. };
  33097. return BoxGeometry;
  33098. }(_PrimitiveGeometry));
  33099. BABYLON.BoxGeometry = BoxGeometry;
  33100. /**
  33101. * Creates a sphere geometry
  33102. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33103. */
  33104. var SphereGeometry = /** @class */ (function (_super) {
  33105. __extends(SphereGeometry, _super);
  33106. /**
  33107. * Create a new sphere geometry
  33108. * @param id defines the unique ID of the geometry
  33109. * @param scene defines the hosting scene
  33110. * @param segments defines the number of segments to use to create the sphere
  33111. * @param diameter defines the diameter of the sphere
  33112. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33113. * @param mesh defines the hosting mesh (can be null)
  33114. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33115. */
  33116. function SphereGeometry(id, scene,
  33117. /**
  33118. * Defines the number of segments to use to create the sphere
  33119. */
  33120. segments,
  33121. /**
  33122. * Defines the diameter of the sphere
  33123. */
  33124. diameter, canBeRegenerated, mesh,
  33125. /**
  33126. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33127. */
  33128. side) {
  33129. if (mesh === void 0) { mesh = null; }
  33130. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33131. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33132. _this.segments = segments;
  33133. _this.diameter = diameter;
  33134. _this.side = side;
  33135. return _this;
  33136. }
  33137. SphereGeometry.prototype._regenerateVertexData = function () {
  33138. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33139. };
  33140. SphereGeometry.prototype.copy = function (id) {
  33141. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33142. };
  33143. SphereGeometry.prototype.serialize = function () {
  33144. var serializationObject = _super.prototype.serialize.call(this);
  33145. serializationObject.segments = this.segments;
  33146. serializationObject.diameter = this.diameter;
  33147. return serializationObject;
  33148. };
  33149. SphereGeometry.Parse = function (parsedSphere, scene) {
  33150. if (scene.getGeometryByID(parsedSphere.id)) {
  33151. return null; // null since geometry could be something else than a sphere...
  33152. }
  33153. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33154. if (BABYLON.Tags) {
  33155. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33156. }
  33157. scene.pushGeometry(sphere, true);
  33158. return sphere;
  33159. };
  33160. return SphereGeometry;
  33161. }(_PrimitiveGeometry));
  33162. BABYLON.SphereGeometry = SphereGeometry;
  33163. /**
  33164. * Creates a disc geometry
  33165. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33166. */
  33167. var DiscGeometry = /** @class */ (function (_super) {
  33168. __extends(DiscGeometry, _super);
  33169. /**
  33170. * Creates a new disc geometry
  33171. * @param id defines the unique ID of the geometry
  33172. * @param scene defines the hosting scene
  33173. * @param radius defines the radius of the disc
  33174. * @param tessellation defines the tesselation factor to apply to the disc
  33175. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33176. * @param mesh defines the hosting mesh (can be null)
  33177. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33178. */
  33179. function DiscGeometry(id, scene,
  33180. /**
  33181. * Defines the radius of the disc
  33182. */
  33183. radius,
  33184. /**
  33185. * Defines the tesselation factor to apply to the disc
  33186. */
  33187. tessellation, canBeRegenerated, mesh,
  33188. /**
  33189. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33190. */
  33191. side) {
  33192. if (mesh === void 0) { mesh = null; }
  33193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33194. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33195. _this.radius = radius;
  33196. _this.tessellation = tessellation;
  33197. _this.side = side;
  33198. return _this;
  33199. }
  33200. DiscGeometry.prototype._regenerateVertexData = function () {
  33201. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33202. };
  33203. DiscGeometry.prototype.copy = function (id) {
  33204. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33205. };
  33206. return DiscGeometry;
  33207. }(_PrimitiveGeometry));
  33208. BABYLON.DiscGeometry = DiscGeometry;
  33209. /**
  33210. * Creates a new cylinder geometry
  33211. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33212. */
  33213. var CylinderGeometry = /** @class */ (function (_super) {
  33214. __extends(CylinderGeometry, _super);
  33215. /**
  33216. * Creates a new cylinder geometry
  33217. * @param id defines the unique ID of the geometry
  33218. * @param scene defines the hosting scene
  33219. * @param height defines the height of the cylinder
  33220. * @param diameterTop defines the diameter of the cylinder's top cap
  33221. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33222. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33223. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33224. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33225. * @param mesh defines the hosting mesh (can be null)
  33226. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33227. */
  33228. function CylinderGeometry(id, scene,
  33229. /**
  33230. * Defines the height of the cylinder
  33231. */
  33232. height,
  33233. /**
  33234. * Defines the diameter of the cylinder's top cap
  33235. */
  33236. diameterTop,
  33237. /**
  33238. * Defines the diameter of the cylinder's bottom cap
  33239. */
  33240. diameterBottom,
  33241. /**
  33242. * Defines the tessellation factor to apply to the cylinder
  33243. */
  33244. tessellation,
  33245. /**
  33246. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33247. */
  33248. subdivisions, canBeRegenerated, mesh,
  33249. /**
  33250. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33251. */
  33252. side) {
  33253. if (subdivisions === void 0) { subdivisions = 1; }
  33254. if (mesh === void 0) { mesh = null; }
  33255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33257. _this.height = height;
  33258. _this.diameterTop = diameterTop;
  33259. _this.diameterBottom = diameterBottom;
  33260. _this.tessellation = tessellation;
  33261. _this.subdivisions = subdivisions;
  33262. _this.side = side;
  33263. return _this;
  33264. }
  33265. CylinderGeometry.prototype._regenerateVertexData = function () {
  33266. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33267. };
  33268. CylinderGeometry.prototype.copy = function (id) {
  33269. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33270. };
  33271. CylinderGeometry.prototype.serialize = function () {
  33272. var serializationObject = _super.prototype.serialize.call(this);
  33273. serializationObject.height = this.height;
  33274. serializationObject.diameterTop = this.diameterTop;
  33275. serializationObject.diameterBottom = this.diameterBottom;
  33276. serializationObject.tessellation = this.tessellation;
  33277. return serializationObject;
  33278. };
  33279. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33280. if (scene.getGeometryByID(parsedCylinder.id)) {
  33281. return null; // null since geometry could be something else than a cylinder...
  33282. }
  33283. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33284. if (BABYLON.Tags) {
  33285. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33286. }
  33287. scene.pushGeometry(cylinder, true);
  33288. return cylinder;
  33289. };
  33290. return CylinderGeometry;
  33291. }(_PrimitiveGeometry));
  33292. BABYLON.CylinderGeometry = CylinderGeometry;
  33293. /**
  33294. * Creates a new torus geometry
  33295. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33296. */
  33297. var TorusGeometry = /** @class */ (function (_super) {
  33298. __extends(TorusGeometry, _super);
  33299. /**
  33300. * Creates a new torus geometry
  33301. * @param id defines the unique ID of the geometry
  33302. * @param scene defines the hosting scene
  33303. * @param diameter defines the diameter of the torus
  33304. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33305. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33306. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33307. * @param mesh defines the hosting mesh (can be null)
  33308. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33309. */
  33310. function TorusGeometry(id, scene,
  33311. /**
  33312. * Defines the diameter of the torus
  33313. */
  33314. diameter,
  33315. /**
  33316. * Defines the thickness of the torus (ie. internal diameter)
  33317. */
  33318. thickness,
  33319. /**
  33320. * Defines the tesselation factor to apply to the torus
  33321. */
  33322. tessellation, canBeRegenerated, mesh,
  33323. /**
  33324. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33325. */
  33326. side) {
  33327. if (mesh === void 0) { mesh = null; }
  33328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33329. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33330. _this.diameter = diameter;
  33331. _this.thickness = thickness;
  33332. _this.tessellation = tessellation;
  33333. _this.side = side;
  33334. return _this;
  33335. }
  33336. TorusGeometry.prototype._regenerateVertexData = function () {
  33337. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33338. };
  33339. TorusGeometry.prototype.copy = function (id) {
  33340. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33341. };
  33342. TorusGeometry.prototype.serialize = function () {
  33343. var serializationObject = _super.prototype.serialize.call(this);
  33344. serializationObject.diameter = this.diameter;
  33345. serializationObject.thickness = this.thickness;
  33346. serializationObject.tessellation = this.tessellation;
  33347. return serializationObject;
  33348. };
  33349. TorusGeometry.Parse = function (parsedTorus, scene) {
  33350. if (scene.getGeometryByID(parsedTorus.id)) {
  33351. return null; // null since geometry could be something else than a torus...
  33352. }
  33353. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33354. if (BABYLON.Tags) {
  33355. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33356. }
  33357. scene.pushGeometry(torus, true);
  33358. return torus;
  33359. };
  33360. return TorusGeometry;
  33361. }(_PrimitiveGeometry));
  33362. BABYLON.TorusGeometry = TorusGeometry;
  33363. /**
  33364. * Creates a new ground geometry
  33365. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33366. */
  33367. var GroundGeometry = /** @class */ (function (_super) {
  33368. __extends(GroundGeometry, _super);
  33369. /**
  33370. * Creates a new ground geometry
  33371. * @param id defines the unique ID of the geometry
  33372. * @param scene defines the hosting scene
  33373. * @param width defines the width of the ground
  33374. * @param height defines the height of the ground
  33375. * @param subdivisions defines the subdivisions to apply to the ground
  33376. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33377. * @param mesh defines the hosting mesh (can be null)
  33378. */
  33379. function GroundGeometry(id, scene,
  33380. /**
  33381. * Defines the width of the ground
  33382. */
  33383. width,
  33384. /**
  33385. * Defines the height of the ground
  33386. */
  33387. height,
  33388. /**
  33389. * Defines the subdivisions to apply to the ground
  33390. */
  33391. subdivisions, canBeRegenerated, mesh) {
  33392. if (mesh === void 0) { mesh = null; }
  33393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33394. _this.width = width;
  33395. _this.height = height;
  33396. _this.subdivisions = subdivisions;
  33397. return _this;
  33398. }
  33399. GroundGeometry.prototype._regenerateVertexData = function () {
  33400. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33401. };
  33402. GroundGeometry.prototype.copy = function (id) {
  33403. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33404. };
  33405. GroundGeometry.prototype.serialize = function () {
  33406. var serializationObject = _super.prototype.serialize.call(this);
  33407. serializationObject.width = this.width;
  33408. serializationObject.height = this.height;
  33409. serializationObject.subdivisions = this.subdivisions;
  33410. return serializationObject;
  33411. };
  33412. GroundGeometry.Parse = function (parsedGround, scene) {
  33413. if (scene.getGeometryByID(parsedGround.id)) {
  33414. return null; // null since geometry could be something else than a ground...
  33415. }
  33416. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33417. if (BABYLON.Tags) {
  33418. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33419. }
  33420. scene.pushGeometry(ground, true);
  33421. return ground;
  33422. };
  33423. return GroundGeometry;
  33424. }(_PrimitiveGeometry));
  33425. BABYLON.GroundGeometry = GroundGeometry;
  33426. /**
  33427. * Creates a tiled ground geometry
  33428. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33429. */
  33430. var TiledGroundGeometry = /** @class */ (function (_super) {
  33431. __extends(TiledGroundGeometry, _super);
  33432. /**
  33433. * Creates a tiled ground geometry
  33434. * @param id defines the unique ID of the geometry
  33435. * @param scene defines the hosting scene
  33436. * @param xmin defines the minimum value on X axis
  33437. * @param zmin defines the minimum value on Z axis
  33438. * @param xmax defines the maximum value on X axis
  33439. * @param zmax defines the maximum value on Z axis
  33440. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33441. * @param precision defines the precision to use when computing the tiles
  33442. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33443. * @param mesh defines the hosting mesh (can be null)
  33444. */
  33445. function TiledGroundGeometry(id, scene,
  33446. /**
  33447. * Defines the minimum value on X axis
  33448. */
  33449. xmin,
  33450. /**
  33451. * Defines the minimum value on Z axis
  33452. */
  33453. zmin,
  33454. /**
  33455. * Defines the maximum value on X axis
  33456. */
  33457. xmax,
  33458. /**
  33459. * Defines the maximum value on Z axis
  33460. */
  33461. zmax,
  33462. /**
  33463. * Defines the subdivisions to apply to the ground
  33464. */
  33465. subdivisions,
  33466. /**
  33467. * Defines the precision to use when computing the tiles
  33468. */
  33469. precision, canBeRegenerated, mesh) {
  33470. if (mesh === void 0) { mesh = null; }
  33471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33472. _this.xmin = xmin;
  33473. _this.zmin = zmin;
  33474. _this.xmax = xmax;
  33475. _this.zmax = zmax;
  33476. _this.subdivisions = subdivisions;
  33477. _this.precision = precision;
  33478. return _this;
  33479. }
  33480. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33481. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33482. };
  33483. TiledGroundGeometry.prototype.copy = function (id) {
  33484. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33485. };
  33486. return TiledGroundGeometry;
  33487. }(_PrimitiveGeometry));
  33488. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33489. /**
  33490. * Creates a plane geometry
  33491. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33492. */
  33493. var PlaneGeometry = /** @class */ (function (_super) {
  33494. __extends(PlaneGeometry, _super);
  33495. /**
  33496. * Creates a plane geometry
  33497. * @param id defines the unique ID of the geometry
  33498. * @param scene defines the hosting scene
  33499. * @param size defines the size of the plane (width === height)
  33500. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33501. * @param mesh defines the hosting mesh (can be null)
  33502. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33503. */
  33504. function PlaneGeometry(id, scene,
  33505. /**
  33506. * Defines the size of the plane (width === height)
  33507. */
  33508. size, canBeRegenerated, mesh,
  33509. /**
  33510. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33511. */
  33512. side) {
  33513. if (mesh === void 0) { mesh = null; }
  33514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33516. _this.size = size;
  33517. _this.side = side;
  33518. return _this;
  33519. }
  33520. PlaneGeometry.prototype._regenerateVertexData = function () {
  33521. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33522. };
  33523. PlaneGeometry.prototype.copy = function (id) {
  33524. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33525. };
  33526. PlaneGeometry.prototype.serialize = function () {
  33527. var serializationObject = _super.prototype.serialize.call(this);
  33528. serializationObject.size = this.size;
  33529. return serializationObject;
  33530. };
  33531. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33532. if (scene.getGeometryByID(parsedPlane.id)) {
  33533. return null; // null since geometry could be something else than a ground...
  33534. }
  33535. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33536. if (BABYLON.Tags) {
  33537. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33538. }
  33539. scene.pushGeometry(plane, true);
  33540. return plane;
  33541. };
  33542. return PlaneGeometry;
  33543. }(_PrimitiveGeometry));
  33544. BABYLON.PlaneGeometry = PlaneGeometry;
  33545. /**
  33546. * Creates a torus knot geometry
  33547. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  33548. */
  33549. var TorusKnotGeometry = /** @class */ (function (_super) {
  33550. __extends(TorusKnotGeometry, _super);
  33551. /**
  33552. * Creates a torus knot geometry
  33553. * @param id defines the unique ID of the geometry
  33554. * @param scene defines the hosting scene
  33555. * @param radius defines the radius of the torus knot
  33556. * @param tube defines the thickness of the torus knot tube
  33557. * @param radialSegments defines the number of radial segments
  33558. * @param tubularSegments defines the number of tubular segments
  33559. * @param p defines the first number of windings
  33560. * @param q defines the second number of windings
  33561. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33562. * @param mesh defines the hosting mesh (can be null)
  33563. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33564. */
  33565. function TorusKnotGeometry(id, scene,
  33566. /**
  33567. * Defines the radius of the torus knot
  33568. */
  33569. radius,
  33570. /**
  33571. * Defines the thickness of the torus knot tube
  33572. */
  33573. tube,
  33574. /**
  33575. * Defines the number of radial segments
  33576. */
  33577. radialSegments,
  33578. /**
  33579. * Defines the number of tubular segments
  33580. */
  33581. tubularSegments,
  33582. /**
  33583. * Defines the first number of windings
  33584. */
  33585. p,
  33586. /**
  33587. * Defines the second number of windings
  33588. */
  33589. q, canBeRegenerated, mesh,
  33590. /**
  33591. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33592. */
  33593. side) {
  33594. if (mesh === void 0) { mesh = null; }
  33595. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33596. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33597. _this.radius = radius;
  33598. _this.tube = tube;
  33599. _this.radialSegments = radialSegments;
  33600. _this.tubularSegments = tubularSegments;
  33601. _this.p = p;
  33602. _this.q = q;
  33603. _this.side = side;
  33604. return _this;
  33605. }
  33606. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  33607. 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 });
  33608. };
  33609. TorusKnotGeometry.prototype.copy = function (id) {
  33610. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33611. };
  33612. TorusKnotGeometry.prototype.serialize = function () {
  33613. var serializationObject = _super.prototype.serialize.call(this);
  33614. serializationObject.radius = this.radius;
  33615. serializationObject.tube = this.tube;
  33616. serializationObject.radialSegments = this.radialSegments;
  33617. serializationObject.tubularSegments = this.tubularSegments;
  33618. serializationObject.p = this.p;
  33619. serializationObject.q = this.q;
  33620. return serializationObject;
  33621. };
  33622. ;
  33623. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  33624. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33625. return null; // null since geometry could be something else than a ground...
  33626. }
  33627. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33628. if (BABYLON.Tags) {
  33629. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33630. }
  33631. scene.pushGeometry(torusKnot, true);
  33632. return torusKnot;
  33633. };
  33634. return TorusKnotGeometry;
  33635. }(_PrimitiveGeometry));
  33636. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  33637. //}
  33638. })(BABYLON || (BABYLON = {}));
  33639. //# sourceMappingURL=babylon.geometry.js.map
  33640. var BABYLON;
  33641. (function (BABYLON) {
  33642. var PostProcessManager = /** @class */ (function () {
  33643. function PostProcessManager(scene) {
  33644. this._vertexBuffers = {};
  33645. this._scene = scene;
  33646. }
  33647. PostProcessManager.prototype._prepareBuffers = function () {
  33648. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  33649. return;
  33650. }
  33651. // VBO
  33652. var vertices = [];
  33653. vertices.push(1, 1);
  33654. vertices.push(-1, 1);
  33655. vertices.push(-1, -1);
  33656. vertices.push(1, -1);
  33657. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33658. this._buildIndexBuffer();
  33659. };
  33660. PostProcessManager.prototype._buildIndexBuffer = function () {
  33661. // Indices
  33662. var indices = [];
  33663. indices.push(0);
  33664. indices.push(1);
  33665. indices.push(2);
  33666. indices.push(0);
  33667. indices.push(2);
  33668. indices.push(3);
  33669. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  33670. };
  33671. PostProcessManager.prototype._rebuild = function () {
  33672. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33673. if (!vb) {
  33674. return;
  33675. }
  33676. vb._rebuild();
  33677. this._buildIndexBuffer();
  33678. };
  33679. // Methods
  33680. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  33681. if (sourceTexture === void 0) { sourceTexture = null; }
  33682. if (postProcesses === void 0) { postProcesses = null; }
  33683. var camera = this._scene.activeCamera;
  33684. if (!camera) {
  33685. return false;
  33686. }
  33687. var postProcesses = postProcesses || camera._postProcesses;
  33688. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33689. return false;
  33690. }
  33691. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33692. return true;
  33693. };
  33694. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33695. if (targetTexture === void 0) { targetTexture = null; }
  33696. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33697. var engine = this._scene.getEngine();
  33698. for (var index = 0; index < postProcesses.length; index++) {
  33699. if (index < postProcesses.length - 1) {
  33700. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33701. }
  33702. else {
  33703. if (targetTexture) {
  33704. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33705. }
  33706. else {
  33707. engine.restoreDefaultFramebuffer();
  33708. }
  33709. }
  33710. var pp = postProcesses[index];
  33711. var effect = pp.apply();
  33712. if (effect) {
  33713. pp.onBeforeRenderObservable.notifyObservers(effect);
  33714. // VBOs
  33715. this._prepareBuffers();
  33716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33717. // Draw order
  33718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33719. pp.onAfterRenderObservable.notifyObservers(effect);
  33720. }
  33721. }
  33722. // Restore depth buffer
  33723. engine.setDepthBuffer(true);
  33724. engine.setDepthWrite(true);
  33725. };
  33726. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33727. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33728. var camera = this._scene.activeCamera;
  33729. if (!camera) {
  33730. return;
  33731. }
  33732. postProcesses = postProcesses || camera._postProcesses;
  33733. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33734. return;
  33735. }
  33736. var engine = this._scene.getEngine();
  33737. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33738. if (index < len - 1) {
  33739. postProcesses[index + 1].activate(camera, targetTexture);
  33740. }
  33741. else {
  33742. if (targetTexture) {
  33743. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33744. }
  33745. else {
  33746. engine.restoreDefaultFramebuffer();
  33747. }
  33748. }
  33749. if (doNotPresent) {
  33750. break;
  33751. }
  33752. var pp = postProcesses[index];
  33753. var effect = pp.apply();
  33754. if (effect) {
  33755. pp.onBeforeRenderObservable.notifyObservers(effect);
  33756. // VBOs
  33757. this._prepareBuffers();
  33758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33759. // Draw order
  33760. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33761. pp.onAfterRenderObservable.notifyObservers(effect);
  33762. }
  33763. }
  33764. // Restore states
  33765. engine.setDepthBuffer(true);
  33766. engine.setDepthWrite(true);
  33767. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33768. };
  33769. PostProcessManager.prototype.dispose = function () {
  33770. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33771. if (buffer) {
  33772. buffer.dispose();
  33773. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33774. }
  33775. if (this._indexBuffer) {
  33776. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33777. this._indexBuffer = null;
  33778. }
  33779. };
  33780. return PostProcessManager;
  33781. }());
  33782. BABYLON.PostProcessManager = PostProcessManager;
  33783. })(BABYLON || (BABYLON = {}));
  33784. //# sourceMappingURL=babylon.postProcessManager.js.map
  33785. var BABYLON;
  33786. (function (BABYLON) {
  33787. /**
  33788. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33789. */
  33790. var PerformanceMonitor = /** @class */ (function () {
  33791. /**
  33792. * constructor
  33793. * @param frameSampleSize The number of samples required to saturate the sliding window
  33794. */
  33795. function PerformanceMonitor(frameSampleSize) {
  33796. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33797. this._enabled = true;
  33798. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33799. }
  33800. /**
  33801. * Samples current frame
  33802. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33803. */
  33804. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33805. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33806. if (!this._enabled)
  33807. return;
  33808. if (this._lastFrameTimeMs != null) {
  33809. var dt = timeMs - this._lastFrameTimeMs;
  33810. this._rollingFrameTime.add(dt);
  33811. }
  33812. this._lastFrameTimeMs = timeMs;
  33813. };
  33814. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33815. /**
  33816. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33817. * @return Average frame time in milliseconds
  33818. */
  33819. get: function () {
  33820. return this._rollingFrameTime.average;
  33821. },
  33822. enumerable: true,
  33823. configurable: true
  33824. });
  33825. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33826. /**
  33827. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33828. * @return Frame time variance in milliseconds squared
  33829. */
  33830. get: function () {
  33831. return this._rollingFrameTime.variance;
  33832. },
  33833. enumerable: true,
  33834. configurable: true
  33835. });
  33836. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33837. /**
  33838. * Returns the frame time of the most recent frame
  33839. * @return Frame time in milliseconds
  33840. */
  33841. get: function () {
  33842. return this._rollingFrameTime.history(0);
  33843. },
  33844. enumerable: true,
  33845. configurable: true
  33846. });
  33847. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33848. /**
  33849. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33850. * @return Framerate in frames per second
  33851. */
  33852. get: function () {
  33853. return 1000.0 / this._rollingFrameTime.average;
  33854. },
  33855. enumerable: true,
  33856. configurable: true
  33857. });
  33858. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33859. /**
  33860. * Returns the average framerate in frames per second using the most recent frame time
  33861. * @return Framerate in frames per second
  33862. */
  33863. get: function () {
  33864. var history = this._rollingFrameTime.history(0);
  33865. if (history === 0) {
  33866. return 0;
  33867. }
  33868. return 1000.0 / history;
  33869. },
  33870. enumerable: true,
  33871. configurable: true
  33872. });
  33873. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33874. /**
  33875. * Returns true if enough samples have been taken to completely fill the sliding window
  33876. * @return true if saturated
  33877. */
  33878. get: function () {
  33879. return this._rollingFrameTime.isSaturated();
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. /**
  33885. * Enables contributions to the sliding window sample set
  33886. */
  33887. PerformanceMonitor.prototype.enable = function () {
  33888. this._enabled = true;
  33889. };
  33890. /**
  33891. * Disables contributions to the sliding window sample set
  33892. * Samples will not be interpolated over the disabled period
  33893. */
  33894. PerformanceMonitor.prototype.disable = function () {
  33895. this._enabled = false;
  33896. //clear last sample to avoid interpolating over the disabled period when next enabled
  33897. this._lastFrameTimeMs = null;
  33898. };
  33899. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33900. /**
  33901. * Returns true if sampling is enabled
  33902. * @return true if enabled
  33903. */
  33904. get: function () {
  33905. return this._enabled;
  33906. },
  33907. enumerable: true,
  33908. configurable: true
  33909. });
  33910. /**
  33911. * Resets performance monitor
  33912. */
  33913. PerformanceMonitor.prototype.reset = function () {
  33914. //clear last sample to avoid interpolating over the disabled period when next enabled
  33915. this._lastFrameTimeMs = null;
  33916. //wipe record
  33917. this._rollingFrameTime.reset();
  33918. };
  33919. return PerformanceMonitor;
  33920. }());
  33921. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33922. /**
  33923. * RollingAverage
  33924. *
  33925. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33926. */
  33927. var RollingAverage = /** @class */ (function () {
  33928. /**
  33929. * constructor
  33930. * @param length The number of samples required to saturate the sliding window
  33931. */
  33932. function RollingAverage(length) {
  33933. this._samples = new Array(length);
  33934. this.reset();
  33935. }
  33936. /**
  33937. * Adds a sample to the sample set
  33938. * @param v The sample value
  33939. */
  33940. RollingAverage.prototype.add = function (v) {
  33941. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33942. var delta;
  33943. //we need to check if we've already wrapped round
  33944. if (this.isSaturated()) {
  33945. //remove bottom of stack from mean
  33946. var bottomValue = this._samples[this._pos];
  33947. delta = bottomValue - this.average;
  33948. this.average -= delta / (this._sampleCount - 1);
  33949. this._m2 -= delta * (bottomValue - this.average);
  33950. }
  33951. else {
  33952. this._sampleCount++;
  33953. }
  33954. //add new value to mean
  33955. delta = v - this.average;
  33956. this.average += delta / (this._sampleCount);
  33957. this._m2 += delta * (v - this.average);
  33958. //set the new variance
  33959. this.variance = this._m2 / (this._sampleCount - 1);
  33960. this._samples[this._pos] = v;
  33961. this._pos++;
  33962. this._pos %= this._samples.length; //positive wrap around
  33963. };
  33964. /**
  33965. * Returns previously added values or null if outside of history or outside the sliding window domain
  33966. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33967. * @return Value previously recorded with add() or null if outside of range
  33968. */
  33969. RollingAverage.prototype.history = function (i) {
  33970. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33971. return 0;
  33972. }
  33973. var i0 = this._wrapPosition(this._pos - 1.0);
  33974. return this._samples[this._wrapPosition(i0 - i)];
  33975. };
  33976. /**
  33977. * Returns true if enough samples have been taken to completely fill the sliding window
  33978. * @return true if sample-set saturated
  33979. */
  33980. RollingAverage.prototype.isSaturated = function () {
  33981. return this._sampleCount >= this._samples.length;
  33982. };
  33983. /**
  33984. * Resets the rolling average (equivalent to 0 samples taken so far)
  33985. */
  33986. RollingAverage.prototype.reset = function () {
  33987. this.average = 0;
  33988. this.variance = 0;
  33989. this._sampleCount = 0;
  33990. this._pos = 0;
  33991. this._m2 = 0;
  33992. };
  33993. /**
  33994. * Wraps a value around the sample range boundaries
  33995. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33996. * @return Wrapped position in sample range
  33997. */
  33998. RollingAverage.prototype._wrapPosition = function (i) {
  33999. var max = this._samples.length;
  34000. return ((i % max) + max) % max;
  34001. };
  34002. return RollingAverage;
  34003. }());
  34004. BABYLON.RollingAverage = RollingAverage;
  34005. })(BABYLON || (BABYLON = {}));
  34006. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34007. var BABYLON;
  34008. (function (BABYLON) {
  34009. /**
  34010. * This groups together the common properties used for image processing either in direct forward pass
  34011. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34012. * or not.
  34013. */
  34014. var ImageProcessingConfiguration = /** @class */ (function () {
  34015. function ImageProcessingConfiguration() {
  34016. /**
  34017. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34018. */
  34019. this.colorCurves = new BABYLON.ColorCurves();
  34020. this._colorCurvesEnabled = false;
  34021. this._colorGradingEnabled = false;
  34022. this._colorGradingWithGreenDepth = true;
  34023. this._colorGradingBGR = true;
  34024. this._exposure = 1.0;
  34025. this._toneMappingEnabled = false;
  34026. this._contrast = 1.0;
  34027. /**
  34028. * Vignette stretch size.
  34029. */
  34030. this.vignetteStretch = 0;
  34031. /**
  34032. * Vignette centre X Offset.
  34033. */
  34034. this.vignetteCentreX = 0;
  34035. /**
  34036. * Vignette centre Y Offset.
  34037. */
  34038. this.vignetteCentreY = 0;
  34039. /**
  34040. * Vignette weight or intensity of the vignette effect.
  34041. */
  34042. this.vignetteWeight = 1.5;
  34043. /**
  34044. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34045. * if vignetteEnabled is set to true.
  34046. */
  34047. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34048. /**
  34049. * Camera field of view used by the Vignette effect.
  34050. */
  34051. this.vignetteCameraFov = 0.5;
  34052. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34053. this._vignetteEnabled = false;
  34054. this._applyByPostProcess = false;
  34055. this._isEnabled = true;
  34056. /**
  34057. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34058. * @type {BABYLON.Observable}
  34059. */
  34060. this.onUpdateParameters = new BABYLON.Observable();
  34061. }
  34062. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34063. /**
  34064. * Gets wether the color curves effect is enabled.
  34065. */
  34066. get: function () {
  34067. return this._colorCurvesEnabled;
  34068. },
  34069. /**
  34070. * Sets wether the color curves effect is enabled.
  34071. */
  34072. set: function (value) {
  34073. if (this._colorCurvesEnabled === value) {
  34074. return;
  34075. }
  34076. this._colorCurvesEnabled = value;
  34077. this._updateParameters();
  34078. },
  34079. enumerable: true,
  34080. configurable: true
  34081. });
  34082. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34083. /**
  34084. * Gets wether the color grading effect is enabled.
  34085. */
  34086. get: function () {
  34087. return this._colorGradingEnabled;
  34088. },
  34089. /**
  34090. * Sets wether the color grading effect is enabled.
  34091. */
  34092. set: function (value) {
  34093. if (this._colorGradingEnabled === value) {
  34094. return;
  34095. }
  34096. this._colorGradingEnabled = value;
  34097. this._updateParameters();
  34098. },
  34099. enumerable: true,
  34100. configurable: true
  34101. });
  34102. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34103. /**
  34104. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34105. */
  34106. get: function () {
  34107. return this._colorGradingWithGreenDepth;
  34108. },
  34109. /**
  34110. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34111. */
  34112. set: function (value) {
  34113. if (this._colorGradingWithGreenDepth === value) {
  34114. return;
  34115. }
  34116. this._colorGradingWithGreenDepth = value;
  34117. this._updateParameters();
  34118. },
  34119. enumerable: true,
  34120. configurable: true
  34121. });
  34122. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34123. /**
  34124. * Gets wether the color grading texture contains BGR values.
  34125. */
  34126. get: function () {
  34127. return this._colorGradingBGR;
  34128. },
  34129. /**
  34130. * Sets wether the color grading texture contains BGR values.
  34131. */
  34132. set: function (value) {
  34133. if (this._colorGradingBGR === value) {
  34134. return;
  34135. }
  34136. this._colorGradingBGR = value;
  34137. this._updateParameters();
  34138. },
  34139. enumerable: true,
  34140. configurable: true
  34141. });
  34142. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34143. /**
  34144. * Gets the Exposure used in the effect.
  34145. */
  34146. get: function () {
  34147. return this._exposure;
  34148. },
  34149. /**
  34150. * Sets the Exposure used in the effect.
  34151. */
  34152. set: function (value) {
  34153. if (this._exposure === value) {
  34154. return;
  34155. }
  34156. this._exposure = value;
  34157. this._updateParameters();
  34158. },
  34159. enumerable: true,
  34160. configurable: true
  34161. });
  34162. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34163. /**
  34164. * Gets wether the tone mapping effect is enabled.
  34165. */
  34166. get: function () {
  34167. return this._toneMappingEnabled;
  34168. },
  34169. /**
  34170. * Sets wether the tone mapping effect is enabled.
  34171. */
  34172. set: function (value) {
  34173. if (this._toneMappingEnabled === value) {
  34174. return;
  34175. }
  34176. this._toneMappingEnabled = value;
  34177. this._updateParameters();
  34178. },
  34179. enumerable: true,
  34180. configurable: true
  34181. });
  34182. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34183. /**
  34184. * Gets the contrast used in the effect.
  34185. */
  34186. get: function () {
  34187. return this._contrast;
  34188. },
  34189. /**
  34190. * Sets the contrast used in the effect.
  34191. */
  34192. set: function (value) {
  34193. if (this._contrast === value) {
  34194. return;
  34195. }
  34196. this._contrast = value;
  34197. this._updateParameters();
  34198. },
  34199. enumerable: true,
  34200. configurable: true
  34201. });
  34202. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34203. /**
  34204. * Gets the vignette blend mode allowing different kind of effect.
  34205. */
  34206. get: function () {
  34207. return this._vignetteBlendMode;
  34208. },
  34209. /**
  34210. * Sets the vignette blend mode allowing different kind of effect.
  34211. */
  34212. set: function (value) {
  34213. if (this._vignetteBlendMode === value) {
  34214. return;
  34215. }
  34216. this._vignetteBlendMode = value;
  34217. this._updateParameters();
  34218. },
  34219. enumerable: true,
  34220. configurable: true
  34221. });
  34222. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34223. /**
  34224. * Gets wether the vignette effect is enabled.
  34225. */
  34226. get: function () {
  34227. return this._vignetteEnabled;
  34228. },
  34229. /**
  34230. * Sets wether the vignette effect is enabled.
  34231. */
  34232. set: function (value) {
  34233. if (this._vignetteEnabled === value) {
  34234. return;
  34235. }
  34236. this._vignetteEnabled = value;
  34237. this._updateParameters();
  34238. },
  34239. enumerable: true,
  34240. configurable: true
  34241. });
  34242. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34243. /**
  34244. * Gets wether the image processing is applied through a post process or not.
  34245. */
  34246. get: function () {
  34247. return this._applyByPostProcess;
  34248. },
  34249. /**
  34250. * Sets wether the image processing is applied through a post process or not.
  34251. */
  34252. set: function (value) {
  34253. if (this._applyByPostProcess === value) {
  34254. return;
  34255. }
  34256. this._applyByPostProcess = value;
  34257. this._updateParameters();
  34258. },
  34259. enumerable: true,
  34260. configurable: true
  34261. });
  34262. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34263. /**
  34264. * Gets wether the image processing is enabled or not.
  34265. */
  34266. get: function () {
  34267. return this._isEnabled;
  34268. },
  34269. /**
  34270. * Sets wether the image processing is enabled or not.
  34271. */
  34272. set: function (value) {
  34273. if (this._isEnabled === value) {
  34274. return;
  34275. }
  34276. this._isEnabled = value;
  34277. this._updateParameters();
  34278. },
  34279. enumerable: true,
  34280. configurable: true
  34281. });
  34282. /**
  34283. * Method called each time the image processing information changes requires to recompile the effect.
  34284. */
  34285. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34286. this.onUpdateParameters.notifyObservers(this);
  34287. };
  34288. ImageProcessingConfiguration.prototype.getClassName = function () {
  34289. return "ImageProcessingConfiguration";
  34290. };
  34291. /**
  34292. * Prepare the list of uniforms associated with the Image Processing effects.
  34293. * @param uniformsList The list of uniforms used in the effect
  34294. * @param defines the list of defines currently in use
  34295. */
  34296. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34297. if (defines.EXPOSURE) {
  34298. uniforms.push("exposureLinear");
  34299. }
  34300. if (defines.CONTRAST) {
  34301. uniforms.push("contrast");
  34302. }
  34303. if (defines.COLORGRADING) {
  34304. uniforms.push("colorTransformSettings");
  34305. }
  34306. if (defines.VIGNETTE) {
  34307. uniforms.push("vInverseScreenSize");
  34308. uniforms.push("vignetteSettings1");
  34309. uniforms.push("vignetteSettings2");
  34310. }
  34311. if (defines.COLORCURVES) {
  34312. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34313. }
  34314. };
  34315. /**
  34316. * Prepare the list of samplers associated with the Image Processing effects.
  34317. * @param uniformsList The list of uniforms used in the effect
  34318. * @param defines the list of defines currently in use
  34319. */
  34320. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34321. if (defines.COLORGRADING) {
  34322. samplersList.push("txColorTransform");
  34323. }
  34324. };
  34325. /**
  34326. * Prepare the list of defines associated to the shader.
  34327. * @param defines the list of defines to complete
  34328. */
  34329. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34330. if (forPostProcess === void 0) { forPostProcess = false; }
  34331. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34332. defines.VIGNETTE = false;
  34333. defines.TONEMAPPING = false;
  34334. defines.CONTRAST = false;
  34335. defines.EXPOSURE = false;
  34336. defines.COLORCURVES = false;
  34337. defines.COLORGRADING = false;
  34338. defines.COLORGRADING3D = false;
  34339. defines.IMAGEPROCESSING = false;
  34340. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34341. return;
  34342. }
  34343. defines.VIGNETTE = this.vignetteEnabled;
  34344. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34345. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34346. defines.TONEMAPPING = this.toneMappingEnabled;
  34347. defines.CONTRAST = (this.contrast !== 1.0);
  34348. defines.EXPOSURE = (this.exposure !== 1.0);
  34349. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34350. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34351. if (defines.COLORGRADING) {
  34352. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34353. }
  34354. else {
  34355. defines.COLORGRADING3D = false;
  34356. }
  34357. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34358. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34359. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34360. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34361. };
  34362. /**
  34363. * Returns true if all the image processing information are ready.
  34364. */
  34365. ImageProcessingConfiguration.prototype.isReady = function () {
  34366. // Color Grading texure can not be none blocking.
  34367. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34368. };
  34369. /**
  34370. * Binds the image processing to the shader.
  34371. * @param effect The effect to bind to
  34372. */
  34373. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34374. if (aspectRatio === void 0) { aspectRatio = 1; }
  34375. // Color Curves
  34376. if (this._colorCurvesEnabled && this.colorCurves) {
  34377. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34378. }
  34379. // Vignette
  34380. if (this._vignetteEnabled) {
  34381. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34382. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34383. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34384. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34385. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34386. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34387. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34388. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34389. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34390. var vignettePower = -2.0 * this.vignetteWeight;
  34391. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34392. }
  34393. // Exposure
  34394. effect.setFloat("exposureLinear", this.exposure);
  34395. // Contrast
  34396. effect.setFloat("contrast", this.contrast);
  34397. // Color transform settings
  34398. if (this.colorGradingTexture) {
  34399. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34400. var textureSize = this.colorGradingTexture.getSize().height;
  34401. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34402. 0.5 / textureSize, // textureOffset
  34403. textureSize, // textureSize
  34404. this.colorGradingTexture.level // weight
  34405. );
  34406. }
  34407. };
  34408. /**
  34409. * Clones the current image processing instance.
  34410. * @return The cloned image processing
  34411. */
  34412. ImageProcessingConfiguration.prototype.clone = function () {
  34413. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34414. };
  34415. /**
  34416. * Serializes the current image processing instance to a json representation.
  34417. * @return a JSON representation
  34418. */
  34419. ImageProcessingConfiguration.prototype.serialize = function () {
  34420. return BABYLON.SerializationHelper.Serialize(this);
  34421. };
  34422. /**
  34423. * Parses the image processing from a json representation.
  34424. * @param source the JSON source to parse
  34425. * @return The parsed image processing
  34426. */
  34427. ImageProcessingConfiguration.Parse = function (source) {
  34428. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34429. };
  34430. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34431. /**
  34432. * Used to apply the vignette as a mix with the pixel color.
  34433. */
  34434. get: function () {
  34435. return this._VIGNETTEMODE_MULTIPLY;
  34436. },
  34437. enumerable: true,
  34438. configurable: true
  34439. });
  34440. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34441. /**
  34442. * Used to apply the vignette as a replacement of the pixel color.
  34443. */
  34444. get: function () {
  34445. return this._VIGNETTEMODE_OPAQUE;
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. // Static constants associated to the image processing.
  34451. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34452. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34453. __decorate([
  34454. BABYLON.serializeAsColorCurves()
  34455. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34456. __decorate([
  34457. BABYLON.serialize()
  34458. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34459. __decorate([
  34460. BABYLON.serializeAsTexture()
  34461. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34462. __decorate([
  34463. BABYLON.serialize()
  34464. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34465. __decorate([
  34466. BABYLON.serialize()
  34467. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34468. __decorate([
  34469. BABYLON.serialize()
  34470. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34471. __decorate([
  34472. BABYLON.serialize()
  34473. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34474. __decorate([
  34475. BABYLON.serialize()
  34476. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34477. __decorate([
  34478. BABYLON.serialize()
  34479. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34480. __decorate([
  34481. BABYLON.serialize()
  34482. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34483. __decorate([
  34484. BABYLON.serialize()
  34485. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34486. __decorate([
  34487. BABYLON.serialize()
  34488. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34489. __decorate([
  34490. BABYLON.serialize()
  34491. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34492. __decorate([
  34493. BABYLON.serializeAsColor4()
  34494. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34495. __decorate([
  34496. BABYLON.serialize()
  34497. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34498. __decorate([
  34499. BABYLON.serialize()
  34500. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34501. __decorate([
  34502. BABYLON.serialize()
  34503. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34504. __decorate([
  34505. BABYLON.serialize()
  34506. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34507. __decorate([
  34508. BABYLON.serialize()
  34509. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34510. return ImageProcessingConfiguration;
  34511. }());
  34512. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  34513. })(BABYLON || (BABYLON = {}));
  34514. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  34515. var BABYLON;
  34516. (function (BABYLON) {
  34517. /**
  34518. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  34519. * It can help converting any input color in a desired output one. This can then be used to create effects
  34520. * from sepia, black and white to sixties or futuristic rendering...
  34521. *
  34522. * The only supported format is currently 3dl.
  34523. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  34524. */
  34525. var ColorGradingTexture = /** @class */ (function (_super) {
  34526. __extends(ColorGradingTexture, _super);
  34527. /**
  34528. * Instantiates a ColorGradingTexture from the following parameters.
  34529. *
  34530. * @param url The location of the color gradind data (currently only supporting 3dl)
  34531. * @param scene The scene the texture will be used in
  34532. */
  34533. function ColorGradingTexture(url, scene) {
  34534. var _this = _super.call(this, scene) || this;
  34535. if (!url) {
  34536. return _this;
  34537. }
  34538. _this._engine = scene.getEngine();
  34539. _this._textureMatrix = BABYLON.Matrix.Identity();
  34540. _this.name = url;
  34541. _this.url = url;
  34542. _this.hasAlpha = false;
  34543. _this.isCube = false;
  34544. _this.is3D = _this._engine.webGLVersion > 1;
  34545. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34546. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34547. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34548. _this.anisotropicFilteringLevel = 1;
  34549. _this._texture = _this._getFromCache(url, true);
  34550. if (!_this._texture) {
  34551. if (!scene.useDelayedTextureLoading) {
  34552. _this.loadTexture();
  34553. }
  34554. else {
  34555. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34556. }
  34557. }
  34558. return _this;
  34559. }
  34560. /**
  34561. * Returns the texture matrix used in most of the material.
  34562. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  34563. */
  34564. ColorGradingTexture.prototype.getTextureMatrix = function () {
  34565. return this._textureMatrix;
  34566. };
  34567. /**
  34568. * Occurs when the file being loaded is a .3dl LUT file.
  34569. */
  34570. ColorGradingTexture.prototype.load3dlTexture = function () {
  34571. var engine = this._engine;
  34572. var texture;
  34573. if (engine.webGLVersion === 1) {
  34574. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34575. }
  34576. else {
  34577. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34578. }
  34579. this._texture = texture;
  34580. var callback = function (text) {
  34581. if (typeof text !== "string") {
  34582. return;
  34583. }
  34584. var data = null;
  34585. var tempData = null;
  34586. var line;
  34587. var lines = text.split('\n');
  34588. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  34589. var maxColor = 0;
  34590. for (var i = 0; i < lines.length; i++) {
  34591. line = lines[i];
  34592. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  34593. continue;
  34594. if (line.indexOf('#') === 0)
  34595. continue;
  34596. var words = line.split(" ");
  34597. if (size === 0) {
  34598. // Number of space + one
  34599. size = words.length;
  34600. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  34601. tempData = new Float32Array(size * size * size * 4);
  34602. continue;
  34603. }
  34604. if (size != 0) {
  34605. var r = Math.max(parseInt(words[0]), 0);
  34606. var g = Math.max(parseInt(words[1]), 0);
  34607. var b = Math.max(parseInt(words[2]), 0);
  34608. maxColor = Math.max(r, maxColor);
  34609. maxColor = Math.max(g, maxColor);
  34610. maxColor = Math.max(b, maxColor);
  34611. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  34612. if (tempData) {
  34613. tempData[pixelStorageIndex + 0] = r;
  34614. tempData[pixelStorageIndex + 1] = g;
  34615. tempData[pixelStorageIndex + 2] = b;
  34616. }
  34617. pixelIndexSlice++;
  34618. if (pixelIndexSlice % size == 0) {
  34619. pixelIndexH++;
  34620. pixelIndexSlice = 0;
  34621. if (pixelIndexH % size == 0) {
  34622. pixelIndexW++;
  34623. pixelIndexH = 0;
  34624. }
  34625. }
  34626. }
  34627. }
  34628. if (tempData && data) {
  34629. for (var i = 0; i < tempData.length; i++) {
  34630. if (i > 0 && (i + 1) % 4 === 0) {
  34631. data[i] = 255;
  34632. }
  34633. else {
  34634. var value = tempData[i];
  34635. data[i] = (value / maxColor * 255);
  34636. }
  34637. }
  34638. }
  34639. if (texture.is3D) {
  34640. texture.updateSize(size, size, size);
  34641. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34642. }
  34643. else {
  34644. texture.updateSize(size * size, size);
  34645. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34646. }
  34647. };
  34648. var scene = this.getScene();
  34649. if (scene) {
  34650. scene._loadFile(this.url, callback);
  34651. }
  34652. else {
  34653. this._engine._loadFile(this.url, callback);
  34654. }
  34655. return this._texture;
  34656. };
  34657. /**
  34658. * Starts the loading process of the texture.
  34659. */
  34660. ColorGradingTexture.prototype.loadTexture = function () {
  34661. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  34662. this.load3dlTexture();
  34663. }
  34664. };
  34665. /**
  34666. * Clones the color gradind texture.
  34667. */
  34668. ColorGradingTexture.prototype.clone = function () {
  34669. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  34670. // Base texture
  34671. newTexture.level = this.level;
  34672. return newTexture;
  34673. };
  34674. /**
  34675. * Called during delayed load for textures.
  34676. */
  34677. ColorGradingTexture.prototype.delayLoad = function () {
  34678. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34679. return;
  34680. }
  34681. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34682. this._texture = this._getFromCache(this.url, true);
  34683. if (!this._texture) {
  34684. this.loadTexture();
  34685. }
  34686. };
  34687. /**
  34688. * Parses a color grading texture serialized by Babylon.
  34689. * @param parsedTexture The texture information being parsedTexture
  34690. * @param scene The scene to load the texture in
  34691. * @param rootUrl The root url of the data assets to load
  34692. * @return A color gradind texture
  34693. */
  34694. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34695. var texture = null;
  34696. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34697. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34698. texture.name = parsedTexture.name;
  34699. texture.level = parsedTexture.level;
  34700. }
  34701. return texture;
  34702. };
  34703. /**
  34704. * Serializes the LUT texture to json format.
  34705. */
  34706. ColorGradingTexture.prototype.serialize = function () {
  34707. if (!this.name) {
  34708. return null;
  34709. }
  34710. var serializationObject = {};
  34711. serializationObject.name = this.name;
  34712. serializationObject.level = this.level;
  34713. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34714. return serializationObject;
  34715. };
  34716. /**
  34717. * Empty line regex stored for GC.
  34718. */
  34719. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34720. return ColorGradingTexture;
  34721. }(BABYLON.BaseTexture));
  34722. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34723. })(BABYLON || (BABYLON = {}));
  34724. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34725. var BABYLON;
  34726. (function (BABYLON) {
  34727. /**
  34728. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34729. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34730. * 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;
  34731. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34732. */
  34733. var ColorCurves = /** @class */ (function () {
  34734. function ColorCurves() {
  34735. this._dirty = true;
  34736. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34737. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34738. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34739. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34740. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34741. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34742. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34743. this._globalHue = 30;
  34744. this._globalDensity = 0;
  34745. this._globalSaturation = 0;
  34746. this._globalExposure = 0;
  34747. this._highlightsHue = 30;
  34748. this._highlightsDensity = 0;
  34749. this._highlightsSaturation = 0;
  34750. this._highlightsExposure = 0;
  34751. this._midtonesHue = 30;
  34752. this._midtonesDensity = 0;
  34753. this._midtonesSaturation = 0;
  34754. this._midtonesExposure = 0;
  34755. this._shadowsHue = 30;
  34756. this._shadowsDensity = 0;
  34757. this._shadowsSaturation = 0;
  34758. this._shadowsExposure = 0;
  34759. }
  34760. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34761. /**
  34762. * Gets the global Hue value.
  34763. * 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).
  34764. */
  34765. get: function () {
  34766. return this._globalHue;
  34767. },
  34768. /**
  34769. * Sets the global Hue value.
  34770. * 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).
  34771. */
  34772. set: function (value) {
  34773. this._globalHue = value;
  34774. this._dirty = true;
  34775. },
  34776. enumerable: true,
  34777. configurable: true
  34778. });
  34779. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34780. /**
  34781. * Gets the global Density value.
  34782. * 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.
  34783. * Values less than zero provide a filter of opposite hue.
  34784. */
  34785. get: function () {
  34786. return this._globalDensity;
  34787. },
  34788. /**
  34789. * Sets the global Density value.
  34790. * 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.
  34791. * Values less than zero provide a filter of opposite hue.
  34792. */
  34793. set: function (value) {
  34794. this._globalDensity = value;
  34795. this._dirty = true;
  34796. },
  34797. enumerable: true,
  34798. configurable: true
  34799. });
  34800. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34801. /**
  34802. * Gets the global Saturation value.
  34803. * 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.
  34804. */
  34805. get: function () {
  34806. return this._globalSaturation;
  34807. },
  34808. /**
  34809. * Sets the global Saturation value.
  34810. * 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.
  34811. */
  34812. set: function (value) {
  34813. this._globalSaturation = value;
  34814. this._dirty = true;
  34815. },
  34816. enumerable: true,
  34817. configurable: true
  34818. });
  34819. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34820. /**
  34821. * Gets the highlights Hue value.
  34822. * 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).
  34823. */
  34824. get: function () {
  34825. return this._highlightsHue;
  34826. },
  34827. /**
  34828. * Sets the highlights Hue value.
  34829. * 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).
  34830. */
  34831. set: function (value) {
  34832. this._highlightsHue = value;
  34833. this._dirty = true;
  34834. },
  34835. enumerable: true,
  34836. configurable: true
  34837. });
  34838. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34839. /**
  34840. * Gets the highlights Density value.
  34841. * 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.
  34842. * Values less than zero provide a filter of opposite hue.
  34843. */
  34844. get: function () {
  34845. return this._highlightsDensity;
  34846. },
  34847. /**
  34848. * Sets the highlights Density value.
  34849. * 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.
  34850. * Values less than zero provide a filter of opposite hue.
  34851. */
  34852. set: function (value) {
  34853. this._highlightsDensity = value;
  34854. this._dirty = true;
  34855. },
  34856. enumerable: true,
  34857. configurable: true
  34858. });
  34859. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34860. /**
  34861. * Gets the highlights Saturation value.
  34862. * 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.
  34863. */
  34864. get: function () {
  34865. return this._highlightsSaturation;
  34866. },
  34867. /**
  34868. * Sets the highlights Saturation value.
  34869. * 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.
  34870. */
  34871. set: function (value) {
  34872. this._highlightsSaturation = value;
  34873. this._dirty = true;
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34879. /**
  34880. * Gets the highlights Exposure value.
  34881. * 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.
  34882. */
  34883. get: function () {
  34884. return this._highlightsExposure;
  34885. },
  34886. /**
  34887. * Sets the highlights Exposure value.
  34888. * 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.
  34889. */
  34890. set: function (value) {
  34891. this._highlightsExposure = value;
  34892. this._dirty = true;
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34898. /**
  34899. * Gets the midtones Hue value.
  34900. * 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).
  34901. */
  34902. get: function () {
  34903. return this._midtonesHue;
  34904. },
  34905. /**
  34906. * Sets the midtones Hue value.
  34907. * 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).
  34908. */
  34909. set: function (value) {
  34910. this._midtonesHue = value;
  34911. this._dirty = true;
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34917. /**
  34918. * Gets the midtones Density value.
  34919. * 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.
  34920. * Values less than zero provide a filter of opposite hue.
  34921. */
  34922. get: function () {
  34923. return this._midtonesDensity;
  34924. },
  34925. /**
  34926. * Sets the midtones Density value.
  34927. * 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.
  34928. * Values less than zero provide a filter of opposite hue.
  34929. */
  34930. set: function (value) {
  34931. this._midtonesDensity = value;
  34932. this._dirty = true;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34938. /**
  34939. * Gets the midtones Saturation value.
  34940. * 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.
  34941. */
  34942. get: function () {
  34943. return this._midtonesSaturation;
  34944. },
  34945. /**
  34946. * Sets the midtones Saturation value.
  34947. * 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.
  34948. */
  34949. set: function (value) {
  34950. this._midtonesSaturation = value;
  34951. this._dirty = true;
  34952. },
  34953. enumerable: true,
  34954. configurable: true
  34955. });
  34956. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34957. /**
  34958. * Gets the midtones Exposure value.
  34959. * 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.
  34960. */
  34961. get: function () {
  34962. return this._midtonesExposure;
  34963. },
  34964. /**
  34965. * Sets the midtones Exposure value.
  34966. * 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.
  34967. */
  34968. set: function (value) {
  34969. this._midtonesExposure = value;
  34970. this._dirty = true;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34976. /**
  34977. * Gets the shadows Hue value.
  34978. * 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).
  34979. */
  34980. get: function () {
  34981. return this._shadowsHue;
  34982. },
  34983. /**
  34984. * Sets the shadows Hue value.
  34985. * 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).
  34986. */
  34987. set: function (value) {
  34988. this._shadowsHue = value;
  34989. this._dirty = true;
  34990. },
  34991. enumerable: true,
  34992. configurable: true
  34993. });
  34994. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34995. /**
  34996. * Gets the shadows Density value.
  34997. * 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.
  34998. * Values less than zero provide a filter of opposite hue.
  34999. */
  35000. get: function () {
  35001. return this._shadowsDensity;
  35002. },
  35003. /**
  35004. * Sets the shadows Density value.
  35005. * 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.
  35006. * Values less than zero provide a filter of opposite hue.
  35007. */
  35008. set: function (value) {
  35009. this._shadowsDensity = value;
  35010. this._dirty = true;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35016. /**
  35017. * Gets the shadows Saturation value.
  35018. * 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.
  35019. */
  35020. get: function () {
  35021. return this._shadowsSaturation;
  35022. },
  35023. /**
  35024. * Sets the shadows Saturation value.
  35025. * 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.
  35026. */
  35027. set: function (value) {
  35028. this._shadowsSaturation = value;
  35029. this._dirty = true;
  35030. },
  35031. enumerable: true,
  35032. configurable: true
  35033. });
  35034. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35035. /**
  35036. * Gets the shadows Exposure value.
  35037. * 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.
  35038. */
  35039. get: function () {
  35040. return this._shadowsExposure;
  35041. },
  35042. /**
  35043. * Sets the shadows Exposure value.
  35044. * 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.
  35045. */
  35046. set: function (value) {
  35047. this._shadowsExposure = value;
  35048. this._dirty = true;
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. ColorCurves.prototype.getClassName = function () {
  35054. return "ColorCurves";
  35055. };
  35056. /**
  35057. * Binds the color curves to the shader.
  35058. * @param colorCurves The color curve to bind
  35059. * @param effect The effect to bind to
  35060. */
  35061. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35062. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35063. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35064. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35065. if (colorCurves._dirty) {
  35066. colorCurves._dirty = false;
  35067. // Fill in global info.
  35068. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35069. // Compute highlights info.
  35070. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35071. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35072. // Compute midtones info.
  35073. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35074. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35075. // Compute shadows info.
  35076. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35077. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35078. // Compute deltas (neutral is midtones).
  35079. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35080. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35081. }
  35082. if (effect) {
  35083. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35084. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35085. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35086. }
  35087. };
  35088. /**
  35089. * Prepare the list of uniforms associated with the ColorCurves effects.
  35090. * @param uniformsList The list of uniforms used in the effect
  35091. */
  35092. ColorCurves.PrepareUniforms = function (uniformsList) {
  35093. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35094. };
  35095. /**
  35096. * Returns color grading data based on a hue, density, saturation and exposure value.
  35097. * @param filterHue The hue of the color filter.
  35098. * @param filterDensity The density of the color filter.
  35099. * @param saturation The saturation.
  35100. * @param exposure The exposure.
  35101. * @param result The result data container.
  35102. */
  35103. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35104. if (hue == null) {
  35105. return;
  35106. }
  35107. hue = ColorCurves.clamp(hue, 0, 360);
  35108. density = ColorCurves.clamp(density, -100, 100);
  35109. saturation = ColorCurves.clamp(saturation, -100, 100);
  35110. exposure = ColorCurves.clamp(exposure, -100, 100);
  35111. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35112. // so that the maximum filter density is only 50% control. This provides fine control
  35113. // for small values and reasonable range.
  35114. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35115. density *= 0.5;
  35116. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35117. if (density < 0) {
  35118. density *= -1;
  35119. hue = (hue + 180) % 360;
  35120. }
  35121. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35122. result.scaleToRef(2, result);
  35123. result.a = 1 + 0.01 * saturation;
  35124. };
  35125. /**
  35126. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35127. * @param value The input slider value in range [-100,100].
  35128. * @returns Adjusted value.
  35129. */
  35130. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35131. value /= 100;
  35132. var x = Math.abs(value);
  35133. x = Math.pow(x, 2);
  35134. if (value < 0) {
  35135. x *= -1;
  35136. }
  35137. x *= 100;
  35138. return x;
  35139. };
  35140. /**
  35141. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35142. * @param hue The hue (H) input.
  35143. * @param saturation The saturation (S) input.
  35144. * @param brightness The brightness (B) input.
  35145. * @result An RGBA color represented as Vector4.
  35146. */
  35147. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35148. var h = ColorCurves.clamp(hue, 0, 360);
  35149. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35150. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35151. if (s === 0) {
  35152. result.r = v;
  35153. result.g = v;
  35154. result.b = v;
  35155. }
  35156. else {
  35157. // sector 0 to 5
  35158. h /= 60;
  35159. var i = Math.floor(h);
  35160. // fractional part of h
  35161. var f = h - i;
  35162. var p = v * (1 - s);
  35163. var q = v * (1 - s * f);
  35164. var t = v * (1 - s * (1 - f));
  35165. switch (i) {
  35166. case 0:
  35167. result.r = v;
  35168. result.g = t;
  35169. result.b = p;
  35170. break;
  35171. case 1:
  35172. result.r = q;
  35173. result.g = v;
  35174. result.b = p;
  35175. break;
  35176. case 2:
  35177. result.r = p;
  35178. result.g = v;
  35179. result.b = t;
  35180. break;
  35181. case 3:
  35182. result.r = p;
  35183. result.g = q;
  35184. result.b = v;
  35185. break;
  35186. case 4:
  35187. result.r = t;
  35188. result.g = p;
  35189. result.b = v;
  35190. break;
  35191. default:// case 5:
  35192. result.r = v;
  35193. result.g = p;
  35194. result.b = q;
  35195. break;
  35196. }
  35197. }
  35198. result.a = 1;
  35199. };
  35200. /**
  35201. * Returns a value clamped between min and max
  35202. * @param value The value to clamp
  35203. * @param min The minimum of value
  35204. * @param max The maximum of value
  35205. * @returns The clamped value.
  35206. */
  35207. ColorCurves.clamp = function (value, min, max) {
  35208. return Math.min(Math.max(value, min), max);
  35209. };
  35210. /**
  35211. * Clones the current color curve instance.
  35212. * @return The cloned curves
  35213. */
  35214. ColorCurves.prototype.clone = function () {
  35215. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35216. };
  35217. /**
  35218. * Serializes the current color curve instance to a json representation.
  35219. * @return a JSON representation
  35220. */
  35221. ColorCurves.prototype.serialize = function () {
  35222. return BABYLON.SerializationHelper.Serialize(this);
  35223. };
  35224. /**
  35225. * Parses the color curve from a json representation.
  35226. * @param source the JSON source to parse
  35227. * @return The parsed curves
  35228. */
  35229. ColorCurves.Parse = function (source) {
  35230. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35231. };
  35232. __decorate([
  35233. BABYLON.serialize()
  35234. ], ColorCurves.prototype, "_globalHue", void 0);
  35235. __decorate([
  35236. BABYLON.serialize()
  35237. ], ColorCurves.prototype, "_globalDensity", void 0);
  35238. __decorate([
  35239. BABYLON.serialize()
  35240. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35241. __decorate([
  35242. BABYLON.serialize()
  35243. ], ColorCurves.prototype, "_globalExposure", void 0);
  35244. __decorate([
  35245. BABYLON.serialize()
  35246. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35247. __decorate([
  35248. BABYLON.serialize()
  35249. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35250. __decorate([
  35251. BABYLON.serialize()
  35252. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35253. __decorate([
  35254. BABYLON.serialize()
  35255. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35256. __decorate([
  35257. BABYLON.serialize()
  35258. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35259. __decorate([
  35260. BABYLON.serialize()
  35261. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35262. __decorate([
  35263. BABYLON.serialize()
  35264. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35265. __decorate([
  35266. BABYLON.serialize()
  35267. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35268. return ColorCurves;
  35269. }());
  35270. BABYLON.ColorCurves = ColorCurves;
  35271. })(BABYLON || (BABYLON = {}));
  35272. //# sourceMappingURL=babylon.colorCurves.js.map
  35273. //# sourceMappingURL=babylon.behavior.js.map
  35274. var BABYLON;
  35275. (function (BABYLON) {
  35276. var MaterialHelper = /** @class */ (function () {
  35277. function MaterialHelper() {
  35278. }
  35279. MaterialHelper.BindEyePosition = function (effect, scene) {
  35280. if (scene._forcedViewPosition) {
  35281. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35282. return;
  35283. }
  35284. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35285. };
  35286. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35287. defines._needUVs = true;
  35288. defines[key] = true;
  35289. if (texture.getTextureMatrix().isIdentity(true)) {
  35290. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35291. if (texture.coordinatesIndex === 0) {
  35292. defines["MAINUV1"] = true;
  35293. }
  35294. else {
  35295. defines["MAINUV2"] = true;
  35296. }
  35297. }
  35298. else {
  35299. defines[key + "DIRECTUV"] = 0;
  35300. }
  35301. };
  35302. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35303. var matrix = texture.getTextureMatrix();
  35304. if (!matrix.isIdentity(true)) {
  35305. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35306. }
  35307. };
  35308. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  35309. if (defines._areMiscDirty) {
  35310. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35311. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35312. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35313. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35314. }
  35315. };
  35316. /**
  35317. * Helper used to prepare the list of defines for shader compilation
  35318. * @param scene defines the current scene
  35319. * @param engine defines the current engine
  35320. * @param defines specifies the list of active defines
  35321. * @param useInstances defines if instances have to be turned on
  35322. * @param alphaTest defines if alpha testing has to be turned on
  35323. */
  35324. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  35325. var changed = false;
  35326. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35327. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35328. changed = true;
  35329. }
  35330. if (defines["ALPHATEST"] !== alphaTest) {
  35331. defines["ALPHATEST"] = !defines["ALPHATEST"];
  35332. changed = true;
  35333. }
  35334. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35335. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35336. changed = true;
  35337. }
  35338. if (defines["INSTANCES"] !== useInstances) {
  35339. defines["INSTANCES"] = useInstances;
  35340. changed = true;
  35341. }
  35342. if (changed) {
  35343. defines.markAsUnprocessed();
  35344. }
  35345. };
  35346. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35347. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35348. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35349. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35350. return false;
  35351. }
  35352. defines._normals = defines._needNormals;
  35353. defines._uvs = defines._needUVs;
  35354. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35355. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35356. defines["TANGENT"] = true;
  35357. }
  35358. if (defines._needUVs) {
  35359. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35360. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35361. }
  35362. else {
  35363. defines["UV1"] = false;
  35364. defines["UV2"] = false;
  35365. }
  35366. if (useVertexColor) {
  35367. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35368. defines["VERTEXCOLOR"] = hasVertexColors;
  35369. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35370. }
  35371. if (useBones) {
  35372. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35373. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35374. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35375. }
  35376. else {
  35377. defines["NUM_BONE_INFLUENCERS"] = 0;
  35378. defines["BonesPerMesh"] = 0;
  35379. }
  35380. }
  35381. if (useMorphTargets) {
  35382. var manager = mesh.morphTargetManager;
  35383. if (manager) {
  35384. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35385. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35386. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35387. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35388. }
  35389. else {
  35390. defines["MORPHTARGETS_TANGENT"] = false;
  35391. defines["MORPHTARGETS_NORMAL"] = false;
  35392. defines["MORPHTARGETS"] = false;
  35393. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35394. }
  35395. }
  35396. return true;
  35397. };
  35398. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35399. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35400. if (disableLighting === void 0) { disableLighting = false; }
  35401. if (!defines._areLightsDirty) {
  35402. return defines._needNormals;
  35403. }
  35404. var lightIndex = 0;
  35405. var needNormals = false;
  35406. var needRebuild = false;
  35407. var lightmapMode = false;
  35408. var shadowEnabled = false;
  35409. var specularEnabled = false;
  35410. if (scene.lightsEnabled && !disableLighting) {
  35411. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35412. var light = _a[_i];
  35413. needNormals = true;
  35414. if (defines["LIGHT" + lightIndex] === undefined) {
  35415. needRebuild = true;
  35416. }
  35417. defines["LIGHT" + lightIndex] = true;
  35418. defines["SPOTLIGHT" + lightIndex] = false;
  35419. defines["HEMILIGHT" + lightIndex] = false;
  35420. defines["POINTLIGHT" + lightIndex] = false;
  35421. defines["DIRLIGHT" + lightIndex] = false;
  35422. var type;
  35423. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35424. type = "SPOTLIGHT" + lightIndex;
  35425. }
  35426. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35427. type = "HEMILIGHT" + lightIndex;
  35428. }
  35429. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35430. type = "POINTLIGHT" + lightIndex;
  35431. }
  35432. else {
  35433. type = "DIRLIGHT" + lightIndex;
  35434. }
  35435. defines[type] = true;
  35436. // Specular
  35437. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35438. specularEnabled = true;
  35439. }
  35440. // Shadows
  35441. defines["SHADOW" + lightIndex] = false;
  35442. defines["SHADOWPCF" + lightIndex] = false;
  35443. defines["SHADOWESM" + lightIndex] = false;
  35444. defines["SHADOWCUBE" + lightIndex] = false;
  35445. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35446. var shadowGenerator = light.getShadowGenerator();
  35447. if (shadowGenerator) {
  35448. shadowEnabled = true;
  35449. shadowGenerator.prepareDefines(defines, lightIndex);
  35450. }
  35451. }
  35452. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35453. lightmapMode = true;
  35454. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35455. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35456. }
  35457. else {
  35458. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35459. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35460. }
  35461. lightIndex++;
  35462. if (lightIndex === maxSimultaneousLights)
  35463. break;
  35464. }
  35465. }
  35466. defines["SPECULARTERM"] = specularEnabled;
  35467. defines["SHADOWS"] = shadowEnabled;
  35468. // Resetting all other lights if any
  35469. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35470. if (defines["LIGHT" + index] !== undefined) {
  35471. defines["LIGHT" + index] = false;
  35472. defines["HEMILIGHT" + lightIndex] = false;
  35473. defines["POINTLIGHT" + lightIndex] = false;
  35474. defines["DIRLIGHT" + lightIndex] = false;
  35475. defines["SPOTLIGHT" + lightIndex] = false;
  35476. defines["SHADOW" + lightIndex] = false;
  35477. }
  35478. }
  35479. var caps = scene.getEngine().getCaps();
  35480. if (defines["SHADOWFLOAT"] === undefined) {
  35481. needRebuild = true;
  35482. }
  35483. defines["SHADOWFLOAT"] = shadowEnabled &&
  35484. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35485. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35486. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35487. if (needRebuild) {
  35488. defines.rebuild();
  35489. }
  35490. return needNormals;
  35491. };
  35492. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35493. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35494. var uniformsList;
  35495. var uniformBuffersList = null;
  35496. if (uniformsListOrOptions.uniformsNames) {
  35497. var options = uniformsListOrOptions;
  35498. uniformsList = options.uniformsNames;
  35499. uniformBuffersList = options.uniformBuffersNames;
  35500. samplersList = options.samplers;
  35501. defines = options.defines;
  35502. maxSimultaneousLights = options.maxSimultaneousLights;
  35503. }
  35504. else {
  35505. uniformsList = uniformsListOrOptions;
  35506. if (!samplersList) {
  35507. samplersList = [];
  35508. }
  35509. }
  35510. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35511. if (!defines["LIGHT" + lightIndex]) {
  35512. break;
  35513. }
  35514. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  35515. if (uniformBuffersList) {
  35516. uniformBuffersList.push("Light" + lightIndex);
  35517. }
  35518. samplersList.push("shadowSampler" + lightIndex);
  35519. }
  35520. if (defines["NUM_MORPH_INFLUENCERS"]) {
  35521. uniformsList.push("morphTargetInfluences");
  35522. }
  35523. };
  35524. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  35525. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35526. if (rank === void 0) { rank = 0; }
  35527. var lightFallbackRank = 0;
  35528. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35529. if (!defines["LIGHT" + lightIndex]) {
  35530. break;
  35531. }
  35532. if (lightIndex > 0) {
  35533. lightFallbackRank = rank + lightIndex;
  35534. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  35535. }
  35536. if (!defines["SHADOWS"]) {
  35537. if (defines["SHADOW" + lightIndex]) {
  35538. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  35539. }
  35540. if (defines["SHADOWPCF" + lightIndex]) {
  35541. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  35542. }
  35543. if (defines["SHADOWESM" + lightIndex]) {
  35544. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  35545. }
  35546. }
  35547. }
  35548. return lightFallbackRank++;
  35549. };
  35550. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  35551. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  35552. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  35553. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  35554. var manager = mesh.morphTargetManager;
  35555. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  35556. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  35557. for (var index = 0; index < influencers; index++) {
  35558. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  35559. if (normal) {
  35560. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  35561. }
  35562. if (tangent) {
  35563. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  35564. }
  35565. if (attribs.length > maxAttributesCount) {
  35566. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  35567. }
  35568. }
  35569. }
  35570. };
  35571. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  35572. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  35573. fallbacks.addCPUSkinningFallback(0, mesh);
  35574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35576. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  35577. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35578. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35579. }
  35580. }
  35581. };
  35582. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  35583. if (defines["INSTANCES"]) {
  35584. attribs.push("world0");
  35585. attribs.push("world1");
  35586. attribs.push("world2");
  35587. attribs.push("world3");
  35588. }
  35589. };
  35590. // Bindings
  35591. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  35592. if (light.shadowEnabled && mesh.receiveShadows) {
  35593. var shadowGenerator = light.getShadowGenerator();
  35594. if (shadowGenerator) {
  35595. shadowGenerator.bindShadowLight(lightIndex, effect);
  35596. }
  35597. }
  35598. };
  35599. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  35600. light.transferToEffect(effect, lightIndex + "");
  35601. };
  35602. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  35603. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35604. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  35605. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  35606. for (var i = 0; i < len; i++) {
  35607. var light = mesh._lightSources[i];
  35608. var iAsString = i.toString();
  35609. var scaledIntensity = light.getScaledIntensity();
  35610. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  35611. MaterialHelper.BindLightProperties(light, effect, i);
  35612. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  35613. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  35614. if (defines["SPECULARTERM"]) {
  35615. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  35616. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  35617. }
  35618. // Shadows
  35619. if (scene.shadowsEnabled) {
  35620. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  35621. }
  35622. light._uniformBuffer.update();
  35623. }
  35624. };
  35625. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  35626. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35627. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35628. effect.setColor3("vFogColor", scene.fogColor);
  35629. }
  35630. };
  35631. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  35632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35633. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  35634. if (matrices && effect) {
  35635. effect.setMatrices("mBones", matrices);
  35636. }
  35637. }
  35638. };
  35639. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  35640. var manager = abstractMesh.morphTargetManager;
  35641. if (!abstractMesh || !manager) {
  35642. return;
  35643. }
  35644. effect.setFloatArray("morphTargetInfluences", manager.influences);
  35645. };
  35646. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  35647. if (defines["LOGARITHMICDEPTH"]) {
  35648. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  35649. }
  35650. };
  35651. MaterialHelper.BindClipPlane = function (effect, scene) {
  35652. if (scene.clipPlane) {
  35653. var clipPlane = scene.clipPlane;
  35654. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35655. }
  35656. };
  35657. return MaterialHelper;
  35658. }());
  35659. BABYLON.MaterialHelper = MaterialHelper;
  35660. })(BABYLON || (BABYLON = {}));
  35661. //# sourceMappingURL=babylon.materialHelper.js.map
  35662. var BABYLON;
  35663. (function (BABYLON) {
  35664. var PushMaterial = /** @class */ (function (_super) {
  35665. __extends(PushMaterial, _super);
  35666. function PushMaterial(name, scene) {
  35667. var _this = _super.call(this, name, scene) || this;
  35668. _this.storeEffectOnSubMeshes = true;
  35669. return _this;
  35670. }
  35671. PushMaterial.prototype.getEffect = function () {
  35672. return this._activeEffect;
  35673. };
  35674. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  35675. if (!mesh) {
  35676. return false;
  35677. }
  35678. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  35679. return true;
  35680. }
  35681. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  35682. };
  35683. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35684. this._activeEffect.setMatrix("world", world);
  35685. };
  35686. PushMaterial.prototype.bind = function (world, mesh) {
  35687. if (!mesh) {
  35688. return;
  35689. }
  35690. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  35691. };
  35692. PushMaterial.prototype._afterBind = function (mesh, effect) {
  35693. if (effect === void 0) { effect = null; }
  35694. _super.prototype._afterBind.call(this, mesh);
  35695. this.getScene()._cachedEffect = effect;
  35696. };
  35697. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35698. if (visibility === void 0) { visibility = 1; }
  35699. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35700. };
  35701. return PushMaterial;
  35702. }(BABYLON.Material));
  35703. BABYLON.PushMaterial = PushMaterial;
  35704. })(BABYLON || (BABYLON = {}));
  35705. //# sourceMappingURL=babylon.pushMaterial.js.map
  35706. var BABYLON;
  35707. (function (BABYLON) {
  35708. var StandardMaterialDefines = /** @class */ (function (_super) {
  35709. __extends(StandardMaterialDefines, _super);
  35710. function StandardMaterialDefines() {
  35711. var _this = _super.call(this) || this;
  35712. _this.MAINUV1 = false;
  35713. _this.MAINUV2 = false;
  35714. _this.DIFFUSE = false;
  35715. _this.DIFFUSEDIRECTUV = 0;
  35716. _this.AMBIENT = false;
  35717. _this.AMBIENTDIRECTUV = 0;
  35718. _this.OPACITY = false;
  35719. _this.OPACITYDIRECTUV = 0;
  35720. _this.OPACITYRGB = false;
  35721. _this.REFLECTION = false;
  35722. _this.EMISSIVE = false;
  35723. _this.EMISSIVEDIRECTUV = 0;
  35724. _this.SPECULAR = false;
  35725. _this.SPECULARDIRECTUV = 0;
  35726. _this.BUMP = false;
  35727. _this.BUMPDIRECTUV = 0;
  35728. _this.PARALLAX = false;
  35729. _this.PARALLAXOCCLUSION = false;
  35730. _this.SPECULAROVERALPHA = false;
  35731. _this.CLIPPLANE = false;
  35732. _this.ALPHATEST = false;
  35733. _this.DEPTHPREPASS = false;
  35734. _this.ALPHAFROMDIFFUSE = false;
  35735. _this.POINTSIZE = false;
  35736. _this.FOG = false;
  35737. _this.SPECULARTERM = false;
  35738. _this.DIFFUSEFRESNEL = false;
  35739. _this.OPACITYFRESNEL = false;
  35740. _this.REFLECTIONFRESNEL = false;
  35741. _this.REFRACTIONFRESNEL = false;
  35742. _this.EMISSIVEFRESNEL = false;
  35743. _this.FRESNEL = false;
  35744. _this.NORMAL = false;
  35745. _this.UV1 = false;
  35746. _this.UV2 = false;
  35747. _this.VERTEXCOLOR = false;
  35748. _this.VERTEXALPHA = false;
  35749. _this.NUM_BONE_INFLUENCERS = 0;
  35750. _this.BonesPerMesh = 0;
  35751. _this.INSTANCES = false;
  35752. _this.GLOSSINESS = false;
  35753. _this.ROUGHNESS = false;
  35754. _this.EMISSIVEASILLUMINATION = false;
  35755. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35756. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35757. _this.LIGHTMAP = false;
  35758. _this.LIGHTMAPDIRECTUV = 0;
  35759. _this.USELIGHTMAPASSHADOWMAP = false;
  35760. _this.REFLECTIONMAP_3D = false;
  35761. _this.REFLECTIONMAP_SPHERICAL = false;
  35762. _this.REFLECTIONMAP_PLANAR = false;
  35763. _this.REFLECTIONMAP_CUBIC = false;
  35764. _this.REFLECTIONMAP_PROJECTION = false;
  35765. _this.REFLECTIONMAP_SKYBOX = false;
  35766. _this.REFLECTIONMAP_EXPLICIT = false;
  35767. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35768. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35769. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35770. _this.INVERTCUBICMAP = false;
  35771. _this.LOGARITHMICDEPTH = false;
  35772. _this.REFRACTION = false;
  35773. _this.REFRACTIONMAP_3D = false;
  35774. _this.REFLECTIONOVERALPHA = false;
  35775. _this.TWOSIDEDLIGHTING = false;
  35776. _this.SHADOWFLOAT = false;
  35777. _this.MORPHTARGETS = false;
  35778. _this.MORPHTARGETS_NORMAL = false;
  35779. _this.MORPHTARGETS_TANGENT = false;
  35780. _this.NUM_MORPH_INFLUENCERS = 0;
  35781. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35782. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35783. _this.IMAGEPROCESSING = false;
  35784. _this.VIGNETTE = false;
  35785. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35786. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35787. _this.TONEMAPPING = false;
  35788. _this.CONTRAST = false;
  35789. _this.COLORCURVES = false;
  35790. _this.COLORGRADING = false;
  35791. _this.COLORGRADING3D = false;
  35792. _this.SAMPLER3DGREENDEPTH = false;
  35793. _this.SAMPLER3DBGRMAP = false;
  35794. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35795. _this.EXPOSURE = false;
  35796. _this.rebuild();
  35797. return _this;
  35798. }
  35799. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35800. var modes = [
  35801. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35802. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35803. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35804. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35805. ];
  35806. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35807. var mode = modes_1[_i];
  35808. this[mode] = (mode === modeToEnable);
  35809. }
  35810. };
  35811. return StandardMaterialDefines;
  35812. }(BABYLON.MaterialDefines));
  35813. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35814. var StandardMaterial = /** @class */ (function (_super) {
  35815. __extends(StandardMaterial, _super);
  35816. function StandardMaterial(name, scene) {
  35817. var _this = _super.call(this, name, scene) || this;
  35818. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35819. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35820. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35821. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35822. _this.specularPower = 64;
  35823. _this._useAlphaFromDiffuseTexture = false;
  35824. _this._useEmissiveAsIllumination = false;
  35825. _this._linkEmissiveWithDiffuse = false;
  35826. _this._useSpecularOverAlpha = false;
  35827. _this._useReflectionOverAlpha = false;
  35828. _this._disableLighting = false;
  35829. _this._useParallax = false;
  35830. _this._useParallaxOcclusion = false;
  35831. _this.parallaxScaleBias = 0.05;
  35832. _this._roughness = 0;
  35833. _this.indexOfRefraction = 0.98;
  35834. _this.invertRefractionY = true;
  35835. _this._useLightmapAsShadowmap = false;
  35836. _this._useReflectionFresnelFromSpecular = false;
  35837. _this._useGlossinessFromSpecularMapAlpha = false;
  35838. _this._maxSimultaneousLights = 4;
  35839. /**
  35840. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35841. */
  35842. _this._invertNormalMapX = false;
  35843. /**
  35844. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35845. */
  35846. _this._invertNormalMapY = false;
  35847. /**
  35848. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35849. */
  35850. _this._twoSidedLighting = false;
  35851. _this._renderTargets = new BABYLON.SmartArray(16);
  35852. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35853. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35854. // Setup the default processing configuration to the scene.
  35855. _this._attachImageProcessingConfiguration(null);
  35856. _this.getRenderTargetTextures = function () {
  35857. _this._renderTargets.reset();
  35858. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35859. _this._renderTargets.push(_this._reflectionTexture);
  35860. }
  35861. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35862. _this._renderTargets.push(_this._refractionTexture);
  35863. }
  35864. return _this._renderTargets;
  35865. };
  35866. return _this;
  35867. }
  35868. ;
  35869. ;
  35870. ;
  35871. ;
  35872. ;
  35873. ;
  35874. ;
  35875. ;
  35876. ;
  35877. ;
  35878. ;
  35879. ;
  35880. ;
  35881. ;
  35882. ;
  35883. ;
  35884. ;
  35885. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35886. /**
  35887. * Gets the image processing configuration used either in this material.
  35888. */
  35889. get: function () {
  35890. return this._imageProcessingConfiguration;
  35891. },
  35892. /**
  35893. * Sets the Default image processing configuration used either in the this material.
  35894. *
  35895. * If sets to null, the scene one is in use.
  35896. */
  35897. set: function (value) {
  35898. this._attachImageProcessingConfiguration(value);
  35899. // Ensure the effect will be rebuilt.
  35900. this._markAllSubMeshesAsTexturesDirty();
  35901. },
  35902. enumerable: true,
  35903. configurable: true
  35904. });
  35905. /**
  35906. * Attaches a new image processing configuration to the Standard Material.
  35907. * @param configuration
  35908. */
  35909. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35910. var _this = this;
  35911. if (configuration === this._imageProcessingConfiguration) {
  35912. return;
  35913. }
  35914. // Detaches observer.
  35915. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35916. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35917. }
  35918. // Pick the scene configuration if needed.
  35919. if (!configuration) {
  35920. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35921. }
  35922. else {
  35923. this._imageProcessingConfiguration = configuration;
  35924. }
  35925. // Attaches observer.
  35926. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35927. _this._markAllSubMeshesAsImageProcessingDirty();
  35928. });
  35929. };
  35930. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35931. /**
  35932. * Gets wether the color curves effect is enabled.
  35933. */
  35934. get: function () {
  35935. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35936. },
  35937. /**
  35938. * Sets wether the color curves effect is enabled.
  35939. */
  35940. set: function (value) {
  35941. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35942. },
  35943. enumerable: true,
  35944. configurable: true
  35945. });
  35946. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35947. /**
  35948. * Gets wether the color grading effect is enabled.
  35949. */
  35950. get: function () {
  35951. return this.imageProcessingConfiguration.colorGradingEnabled;
  35952. },
  35953. /**
  35954. * Gets wether the color grading effect is enabled.
  35955. */
  35956. set: function (value) {
  35957. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35958. },
  35959. enumerable: true,
  35960. configurable: true
  35961. });
  35962. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35963. /**
  35964. * Gets wether tonemapping is enabled or not.
  35965. */
  35966. get: function () {
  35967. return this._imageProcessingConfiguration.toneMappingEnabled;
  35968. },
  35969. /**
  35970. * Sets wether tonemapping is enabled or not
  35971. */
  35972. set: function (value) {
  35973. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35974. },
  35975. enumerable: true,
  35976. configurable: true
  35977. });
  35978. ;
  35979. ;
  35980. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35981. /**
  35982. * The camera exposure used on this material.
  35983. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35984. * This corresponds to a photographic exposure.
  35985. */
  35986. get: function () {
  35987. return this._imageProcessingConfiguration.exposure;
  35988. },
  35989. /**
  35990. * The camera exposure used on this material.
  35991. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35992. * This corresponds to a photographic exposure.
  35993. */
  35994. set: function (value) {
  35995. this._imageProcessingConfiguration.exposure = value;
  35996. },
  35997. enumerable: true,
  35998. configurable: true
  35999. });
  36000. ;
  36001. ;
  36002. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36003. /**
  36004. * Gets The camera contrast used on this material.
  36005. */
  36006. get: function () {
  36007. return this._imageProcessingConfiguration.contrast;
  36008. },
  36009. /**
  36010. * Sets The camera contrast used on this material.
  36011. */
  36012. set: function (value) {
  36013. this._imageProcessingConfiguration.contrast = value;
  36014. },
  36015. enumerable: true,
  36016. configurable: true
  36017. });
  36018. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36019. /**
  36020. * Gets the Color Grading 2D Lookup Texture.
  36021. */
  36022. get: function () {
  36023. return this._imageProcessingConfiguration.colorGradingTexture;
  36024. },
  36025. /**
  36026. * Sets the Color Grading 2D Lookup Texture.
  36027. */
  36028. set: function (value) {
  36029. this._imageProcessingConfiguration.colorGradingTexture = value;
  36030. },
  36031. enumerable: true,
  36032. configurable: true
  36033. });
  36034. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36035. /**
  36036. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36037. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36038. * 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;
  36039. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36040. */
  36041. get: function () {
  36042. return this._imageProcessingConfiguration.colorCurves;
  36043. },
  36044. /**
  36045. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36046. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36047. * 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;
  36048. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36049. */
  36050. set: function (value) {
  36051. this._imageProcessingConfiguration.colorCurves = value;
  36052. },
  36053. enumerable: true,
  36054. configurable: true
  36055. });
  36056. StandardMaterial.prototype.getClassName = function () {
  36057. return "StandardMaterial";
  36058. };
  36059. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36060. get: function () {
  36061. return this._useLogarithmicDepth;
  36062. },
  36063. set: function (value) {
  36064. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36065. this._markAllSubMeshesAsMiscDirty();
  36066. },
  36067. enumerable: true,
  36068. configurable: true
  36069. });
  36070. StandardMaterial.prototype.needAlphaBlending = function () {
  36071. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36072. };
  36073. StandardMaterial.prototype.needAlphaTesting = function () {
  36074. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36075. };
  36076. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36077. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36078. };
  36079. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36080. return this._diffuseTexture;
  36081. };
  36082. /**
  36083. * Child classes can use it to update shaders
  36084. */
  36085. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36086. if (useInstances === void 0) { useInstances = false; }
  36087. if (subMesh.effect && this.isFrozen) {
  36088. if (this._wasPreviouslyReady && subMesh.effect) {
  36089. return true;
  36090. }
  36091. }
  36092. if (!subMesh._materialDefines) {
  36093. subMesh._materialDefines = new StandardMaterialDefines();
  36094. }
  36095. var scene = this.getScene();
  36096. var defines = subMesh._materialDefines;
  36097. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36098. if (defines._renderId === scene.getRenderId()) {
  36099. return true;
  36100. }
  36101. }
  36102. var engine = scene.getEngine();
  36103. // Lights
  36104. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36105. // Textures
  36106. if (defines._areTexturesDirty) {
  36107. defines._needUVs = false;
  36108. defines.MAINUV1 = false;
  36109. defines.MAINUV2 = false;
  36110. if (scene.texturesEnabled) {
  36111. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36112. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36113. return false;
  36114. }
  36115. else {
  36116. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36117. }
  36118. }
  36119. else {
  36120. defines.DIFFUSE = false;
  36121. }
  36122. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36123. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36124. return false;
  36125. }
  36126. else {
  36127. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36128. }
  36129. }
  36130. else {
  36131. defines.AMBIENT = false;
  36132. }
  36133. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36134. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36135. return false;
  36136. }
  36137. else {
  36138. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36139. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36140. }
  36141. }
  36142. else {
  36143. defines.OPACITY = false;
  36144. }
  36145. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36146. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36147. return false;
  36148. }
  36149. else {
  36150. defines._needNormals = true;
  36151. defines.REFLECTION = true;
  36152. defines.ROUGHNESS = (this._roughness > 0);
  36153. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36154. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36155. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36156. switch (this._reflectionTexture.coordinatesMode) {
  36157. case BABYLON.Texture.CUBIC_MODE:
  36158. case BABYLON.Texture.INVCUBIC_MODE:
  36159. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36160. break;
  36161. case BABYLON.Texture.EXPLICIT_MODE:
  36162. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36163. break;
  36164. case BABYLON.Texture.PLANAR_MODE:
  36165. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36166. break;
  36167. case BABYLON.Texture.PROJECTION_MODE:
  36168. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36169. break;
  36170. case BABYLON.Texture.SKYBOX_MODE:
  36171. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36172. break;
  36173. case BABYLON.Texture.SPHERICAL_MODE:
  36174. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36175. break;
  36176. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36177. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36178. break;
  36179. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36180. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36181. break;
  36182. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36183. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36184. break;
  36185. }
  36186. }
  36187. }
  36188. else {
  36189. defines.REFLECTION = false;
  36190. }
  36191. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36192. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36193. return false;
  36194. }
  36195. else {
  36196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36197. }
  36198. }
  36199. else {
  36200. defines.EMISSIVE = false;
  36201. }
  36202. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36203. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36204. return false;
  36205. }
  36206. else {
  36207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36208. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36209. }
  36210. }
  36211. else {
  36212. defines.LIGHTMAP = false;
  36213. }
  36214. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36215. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36216. return false;
  36217. }
  36218. else {
  36219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36220. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36221. }
  36222. }
  36223. else {
  36224. defines.SPECULAR = false;
  36225. }
  36226. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36227. // Bump texure can not be not blocking.
  36228. if (!this._bumpTexture.isReady()) {
  36229. return false;
  36230. }
  36231. else {
  36232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36233. defines.PARALLAX = this._useParallax;
  36234. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36235. }
  36236. }
  36237. else {
  36238. defines.BUMP = false;
  36239. }
  36240. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36241. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36242. return false;
  36243. }
  36244. else {
  36245. defines._needUVs = true;
  36246. defines.REFRACTION = true;
  36247. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36248. }
  36249. }
  36250. else {
  36251. defines.REFRACTION = false;
  36252. }
  36253. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36254. }
  36255. else {
  36256. defines.DIFFUSE = false;
  36257. defines.AMBIENT = false;
  36258. defines.OPACITY = false;
  36259. defines.REFLECTION = false;
  36260. defines.EMISSIVE = false;
  36261. defines.LIGHTMAP = false;
  36262. defines.BUMP = false;
  36263. defines.REFRACTION = false;
  36264. }
  36265. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36266. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36267. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36268. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36269. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36270. }
  36271. if (defines._areImageProcessingDirty) {
  36272. if (!this._imageProcessingConfiguration.isReady()) {
  36273. return false;
  36274. }
  36275. this._imageProcessingConfiguration.prepareDefines(defines);
  36276. }
  36277. if (defines._areFresnelDirty) {
  36278. if (StandardMaterial.FresnelEnabled) {
  36279. // Fresnel
  36280. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36281. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36282. this._reflectionFresnelParameters) {
  36283. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36284. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36285. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36286. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36287. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36288. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36289. defines._needNormals = true;
  36290. defines.FRESNEL = true;
  36291. }
  36292. }
  36293. else {
  36294. defines.FRESNEL = false;
  36295. }
  36296. }
  36297. // Misc.
  36298. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36299. // Attribs
  36300. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36301. // Values that need to be evaluated on every frame
  36302. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  36303. // Get correct effect
  36304. if (defines.isDirty) {
  36305. defines.markAsProcessed();
  36306. scene.resetCachedMaterial();
  36307. // Fallbacks
  36308. var fallbacks = new BABYLON.EffectFallbacks();
  36309. if (defines.REFLECTION) {
  36310. fallbacks.addFallback(0, "REFLECTION");
  36311. }
  36312. if (defines.SPECULAR) {
  36313. fallbacks.addFallback(0, "SPECULAR");
  36314. }
  36315. if (defines.BUMP) {
  36316. fallbacks.addFallback(0, "BUMP");
  36317. }
  36318. if (defines.PARALLAX) {
  36319. fallbacks.addFallback(1, "PARALLAX");
  36320. }
  36321. if (defines.PARALLAXOCCLUSION) {
  36322. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36323. }
  36324. if (defines.SPECULAROVERALPHA) {
  36325. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36326. }
  36327. if (defines.FOG) {
  36328. fallbacks.addFallback(1, "FOG");
  36329. }
  36330. if (defines.POINTSIZE) {
  36331. fallbacks.addFallback(0, "POINTSIZE");
  36332. }
  36333. if (defines.LOGARITHMICDEPTH) {
  36334. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36335. }
  36336. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36337. if (defines.SPECULARTERM) {
  36338. fallbacks.addFallback(0, "SPECULARTERM");
  36339. }
  36340. if (defines.DIFFUSEFRESNEL) {
  36341. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36342. }
  36343. if (defines.OPACITYFRESNEL) {
  36344. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36345. }
  36346. if (defines.REFLECTIONFRESNEL) {
  36347. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36348. }
  36349. if (defines.EMISSIVEFRESNEL) {
  36350. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36351. }
  36352. if (defines.FRESNEL) {
  36353. fallbacks.addFallback(4, "FRESNEL");
  36354. }
  36355. //Attributes
  36356. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36357. if (defines.NORMAL) {
  36358. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36359. }
  36360. if (defines.UV1) {
  36361. attribs.push(BABYLON.VertexBuffer.UVKind);
  36362. }
  36363. if (defines.UV2) {
  36364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36365. }
  36366. if (defines.VERTEXCOLOR) {
  36367. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36368. }
  36369. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36370. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36371. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36372. var shaderName = "default";
  36373. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36374. "vFogInfos", "vFogColor", "pointSize",
  36375. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36376. "mBones",
  36377. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36378. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36379. "logarithmicDepthConstant", "vTangentSpaceParams"
  36380. ];
  36381. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36382. var uniformBuffers = ["Material", "Scene"];
  36383. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36384. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36385. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36386. uniformsNames: uniforms,
  36387. uniformBuffersNames: uniformBuffers,
  36388. samplers: samplers,
  36389. defines: defines,
  36390. maxSimultaneousLights: this._maxSimultaneousLights
  36391. });
  36392. if (this.customShaderNameResolve) {
  36393. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36394. }
  36395. var join = defines.toString();
  36396. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36397. attributes: attribs,
  36398. uniformsNames: uniforms,
  36399. uniformBuffersNames: uniformBuffers,
  36400. samplers: samplers,
  36401. defines: join,
  36402. fallbacks: fallbacks,
  36403. onCompiled: this.onCompiled,
  36404. onError: this.onError,
  36405. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36406. }, engine), defines);
  36407. this.buildUniformLayout();
  36408. }
  36409. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36410. return false;
  36411. }
  36412. defines._renderId = scene.getRenderId();
  36413. this._wasPreviouslyReady = true;
  36414. return true;
  36415. };
  36416. StandardMaterial.prototype.buildUniformLayout = function () {
  36417. // Order is important !
  36418. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36419. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36420. this._uniformBuffer.addUniform("opacityParts", 4);
  36421. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36422. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36423. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36424. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36425. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36426. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36427. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36428. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36429. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36430. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36431. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36432. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36433. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36434. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36435. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36436. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36437. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36438. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36439. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36440. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36441. this._uniformBuffer.addUniform("specularMatrix", 16);
  36442. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36443. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36444. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36445. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36446. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36447. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36448. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36449. this._uniformBuffer.addUniform("pointSize", 1);
  36450. this._uniformBuffer.create();
  36451. };
  36452. StandardMaterial.prototype.unbind = function () {
  36453. if (this._activeEffect) {
  36454. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36455. this._activeEffect.setTexture("reflection2DSampler", null);
  36456. }
  36457. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36458. this._activeEffect.setTexture("refraction2DSampler", null);
  36459. }
  36460. }
  36461. _super.prototype.unbind.call(this);
  36462. };
  36463. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36464. var scene = this.getScene();
  36465. var defines = subMesh._materialDefines;
  36466. if (!defines) {
  36467. return;
  36468. }
  36469. var effect = subMesh.effect;
  36470. if (!effect) {
  36471. return;
  36472. }
  36473. this._activeEffect = effect;
  36474. // Matrices
  36475. this.bindOnlyWorldMatrix(world);
  36476. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36477. // Bones
  36478. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36479. if (mustRebind) {
  36480. this._uniformBuffer.bindToEffect(effect, "Material");
  36481. this.bindViewProjection(effect);
  36482. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36483. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36484. // Fresnel
  36485. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36486. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36487. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36488. }
  36489. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36490. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36491. }
  36492. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36493. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36494. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36495. }
  36496. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36497. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36498. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36499. }
  36500. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36501. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36502. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36503. }
  36504. }
  36505. // Textures
  36506. if (scene.texturesEnabled) {
  36507. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36508. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  36509. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  36510. }
  36511. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36512. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  36513. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36514. }
  36515. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36516. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36517. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36518. }
  36519. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36520. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  36521. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  36522. }
  36523. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36524. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36525. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36526. }
  36527. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36528. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36529. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36530. }
  36531. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36532. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  36533. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  36534. }
  36535. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36536. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  36537. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36538. if (scene._mirroredCameraPosition) {
  36539. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36540. }
  36541. else {
  36542. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36543. }
  36544. }
  36545. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36546. var depth = 1.0;
  36547. if (!this._refractionTexture.isCube) {
  36548. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  36549. if (this._refractionTexture.depth) {
  36550. depth = this._refractionTexture.depth;
  36551. }
  36552. }
  36553. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  36554. }
  36555. }
  36556. // Point size
  36557. if (this.pointsCloud) {
  36558. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36559. }
  36560. if (defines.SPECULARTERM) {
  36561. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  36562. }
  36563. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  36564. // Diffuse
  36565. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  36566. }
  36567. // Textures
  36568. if (scene.texturesEnabled) {
  36569. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36570. effect.setTexture("diffuseSampler", this._diffuseTexture);
  36571. }
  36572. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36573. effect.setTexture("ambientSampler", this._ambientTexture);
  36574. }
  36575. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36576. effect.setTexture("opacitySampler", this._opacityTexture);
  36577. }
  36578. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36579. if (this._reflectionTexture.isCube) {
  36580. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  36581. }
  36582. else {
  36583. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  36584. }
  36585. }
  36586. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36587. effect.setTexture("emissiveSampler", this._emissiveTexture);
  36588. }
  36589. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36590. effect.setTexture("lightmapSampler", this._lightmapTexture);
  36591. }
  36592. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36593. effect.setTexture("specularSampler", this._specularTexture);
  36594. }
  36595. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36596. effect.setTexture("bumpSampler", this._bumpTexture);
  36597. }
  36598. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36599. var depth = 1.0;
  36600. if (this._refractionTexture.isCube) {
  36601. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  36602. }
  36603. else {
  36604. effect.setTexture("refraction2DSampler", this._refractionTexture);
  36605. }
  36606. }
  36607. }
  36608. // Clip plane
  36609. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  36610. // Colors
  36611. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  36612. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  36613. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36614. }
  36615. if (mustRebind || !this.isFrozen) {
  36616. // Lights
  36617. if (scene.lightsEnabled && !this._disableLighting) {
  36618. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  36619. }
  36620. // View
  36621. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  36622. this.bindView(effect);
  36623. }
  36624. // Fog
  36625. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  36626. // Morph targets
  36627. if (defines.NUM_MORPH_INFLUENCERS) {
  36628. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  36629. }
  36630. // Log. depth
  36631. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  36632. // image processing
  36633. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  36634. this._imageProcessingConfiguration.bind(this._activeEffect);
  36635. }
  36636. }
  36637. this._uniformBuffer.update();
  36638. this._afterBind(mesh, this._activeEffect);
  36639. };
  36640. StandardMaterial.prototype.getAnimatables = function () {
  36641. var results = [];
  36642. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  36643. results.push(this._diffuseTexture);
  36644. }
  36645. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36646. results.push(this._ambientTexture);
  36647. }
  36648. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36649. results.push(this._opacityTexture);
  36650. }
  36651. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36652. results.push(this._reflectionTexture);
  36653. }
  36654. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36655. results.push(this._emissiveTexture);
  36656. }
  36657. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  36658. results.push(this._specularTexture);
  36659. }
  36660. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36661. results.push(this._bumpTexture);
  36662. }
  36663. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36664. results.push(this._lightmapTexture);
  36665. }
  36666. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36667. results.push(this._refractionTexture);
  36668. }
  36669. return results;
  36670. };
  36671. StandardMaterial.prototype.getActiveTextures = function () {
  36672. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36673. if (this._diffuseTexture) {
  36674. activeTextures.push(this._diffuseTexture);
  36675. }
  36676. if (this._ambientTexture) {
  36677. activeTextures.push(this._ambientTexture);
  36678. }
  36679. if (this._opacityTexture) {
  36680. activeTextures.push(this._opacityTexture);
  36681. }
  36682. if (this._reflectionTexture) {
  36683. activeTextures.push(this._reflectionTexture);
  36684. }
  36685. if (this._emissiveTexture) {
  36686. activeTextures.push(this._emissiveTexture);
  36687. }
  36688. if (this._specularTexture) {
  36689. activeTextures.push(this._specularTexture);
  36690. }
  36691. if (this._bumpTexture) {
  36692. activeTextures.push(this._bumpTexture);
  36693. }
  36694. if (this._lightmapTexture) {
  36695. activeTextures.push(this._lightmapTexture);
  36696. }
  36697. if (this._refractionTexture) {
  36698. activeTextures.push(this._refractionTexture);
  36699. }
  36700. return activeTextures;
  36701. };
  36702. StandardMaterial.prototype.hasTexture = function (texture) {
  36703. if (_super.prototype.hasTexture.call(this, texture)) {
  36704. return true;
  36705. }
  36706. if (this._diffuseTexture === texture) {
  36707. return true;
  36708. }
  36709. if (this._ambientTexture === texture) {
  36710. return true;
  36711. }
  36712. if (this._opacityTexture === texture) {
  36713. return true;
  36714. }
  36715. if (this._reflectionTexture === texture) {
  36716. return true;
  36717. }
  36718. if (this._emissiveTexture === texture) {
  36719. return true;
  36720. }
  36721. if (this._specularTexture === texture) {
  36722. return true;
  36723. }
  36724. if (this._bumpTexture === texture) {
  36725. return true;
  36726. }
  36727. if (this._lightmapTexture === texture) {
  36728. return true;
  36729. }
  36730. if (this._refractionTexture === texture) {
  36731. return true;
  36732. }
  36733. return false;
  36734. };
  36735. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36736. if (forceDisposeTextures) {
  36737. if (this._diffuseTexture) {
  36738. this._diffuseTexture.dispose();
  36739. }
  36740. if (this._ambientTexture) {
  36741. this._ambientTexture.dispose();
  36742. }
  36743. if (this._opacityTexture) {
  36744. this._opacityTexture.dispose();
  36745. }
  36746. if (this._reflectionTexture) {
  36747. this._reflectionTexture.dispose();
  36748. }
  36749. if (this._emissiveTexture) {
  36750. this._emissiveTexture.dispose();
  36751. }
  36752. if (this._specularTexture) {
  36753. this._specularTexture.dispose();
  36754. }
  36755. if (this._bumpTexture) {
  36756. this._bumpTexture.dispose();
  36757. }
  36758. if (this._lightmapTexture) {
  36759. this._lightmapTexture.dispose();
  36760. }
  36761. if (this._refractionTexture) {
  36762. this._refractionTexture.dispose();
  36763. }
  36764. }
  36765. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36766. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36767. }
  36768. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36769. };
  36770. StandardMaterial.prototype.clone = function (name) {
  36771. var _this = this;
  36772. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36773. result.name = name;
  36774. result.id = name;
  36775. return result;
  36776. };
  36777. StandardMaterial.prototype.serialize = function () {
  36778. return BABYLON.SerializationHelper.Serialize(this);
  36779. };
  36780. // Statics
  36781. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36782. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36783. };
  36784. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36785. get: function () {
  36786. return StandardMaterial._DiffuseTextureEnabled;
  36787. },
  36788. set: function (value) {
  36789. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36790. return;
  36791. }
  36792. StandardMaterial._DiffuseTextureEnabled = value;
  36793. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36794. },
  36795. enumerable: true,
  36796. configurable: true
  36797. });
  36798. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36799. get: function () {
  36800. return StandardMaterial._AmbientTextureEnabled;
  36801. },
  36802. set: function (value) {
  36803. if (StandardMaterial._AmbientTextureEnabled === value) {
  36804. return;
  36805. }
  36806. StandardMaterial._AmbientTextureEnabled = value;
  36807. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36808. },
  36809. enumerable: true,
  36810. configurable: true
  36811. });
  36812. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36813. get: function () {
  36814. return StandardMaterial._OpacityTextureEnabled;
  36815. },
  36816. set: function (value) {
  36817. if (StandardMaterial._OpacityTextureEnabled === value) {
  36818. return;
  36819. }
  36820. StandardMaterial._OpacityTextureEnabled = value;
  36821. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36822. },
  36823. enumerable: true,
  36824. configurable: true
  36825. });
  36826. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36827. get: function () {
  36828. return StandardMaterial._ReflectionTextureEnabled;
  36829. },
  36830. set: function (value) {
  36831. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36832. return;
  36833. }
  36834. StandardMaterial._ReflectionTextureEnabled = value;
  36835. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36836. },
  36837. enumerable: true,
  36838. configurable: true
  36839. });
  36840. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36841. get: function () {
  36842. return StandardMaterial._EmissiveTextureEnabled;
  36843. },
  36844. set: function (value) {
  36845. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36846. return;
  36847. }
  36848. StandardMaterial._EmissiveTextureEnabled = value;
  36849. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36850. },
  36851. enumerable: true,
  36852. configurable: true
  36853. });
  36854. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36855. get: function () {
  36856. return StandardMaterial._SpecularTextureEnabled;
  36857. },
  36858. set: function (value) {
  36859. if (StandardMaterial._SpecularTextureEnabled === value) {
  36860. return;
  36861. }
  36862. StandardMaterial._SpecularTextureEnabled = value;
  36863. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36864. },
  36865. enumerable: true,
  36866. configurable: true
  36867. });
  36868. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36869. get: function () {
  36870. return StandardMaterial._BumpTextureEnabled;
  36871. },
  36872. set: function (value) {
  36873. if (StandardMaterial._BumpTextureEnabled === value) {
  36874. return;
  36875. }
  36876. StandardMaterial._BumpTextureEnabled = value;
  36877. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36878. },
  36879. enumerable: true,
  36880. configurable: true
  36881. });
  36882. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36883. get: function () {
  36884. return StandardMaterial._LightmapTextureEnabled;
  36885. },
  36886. set: function (value) {
  36887. if (StandardMaterial._LightmapTextureEnabled === value) {
  36888. return;
  36889. }
  36890. StandardMaterial._LightmapTextureEnabled = value;
  36891. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36892. },
  36893. enumerable: true,
  36894. configurable: true
  36895. });
  36896. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36897. get: function () {
  36898. return StandardMaterial._RefractionTextureEnabled;
  36899. },
  36900. set: function (value) {
  36901. if (StandardMaterial._RefractionTextureEnabled === value) {
  36902. return;
  36903. }
  36904. StandardMaterial._RefractionTextureEnabled = value;
  36905. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36906. },
  36907. enumerable: true,
  36908. configurable: true
  36909. });
  36910. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36911. get: function () {
  36912. return StandardMaterial._ColorGradingTextureEnabled;
  36913. },
  36914. set: function (value) {
  36915. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36916. return;
  36917. }
  36918. StandardMaterial._ColorGradingTextureEnabled = value;
  36919. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36920. },
  36921. enumerable: true,
  36922. configurable: true
  36923. });
  36924. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36925. get: function () {
  36926. return StandardMaterial._FresnelEnabled;
  36927. },
  36928. set: function (value) {
  36929. if (StandardMaterial._FresnelEnabled === value) {
  36930. return;
  36931. }
  36932. StandardMaterial._FresnelEnabled = value;
  36933. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36934. },
  36935. enumerable: true,
  36936. configurable: true
  36937. });
  36938. // Flags used to enable or disable a type of texture for all Standard Materials
  36939. StandardMaterial._DiffuseTextureEnabled = true;
  36940. StandardMaterial._AmbientTextureEnabled = true;
  36941. StandardMaterial._OpacityTextureEnabled = true;
  36942. StandardMaterial._ReflectionTextureEnabled = true;
  36943. StandardMaterial._EmissiveTextureEnabled = true;
  36944. StandardMaterial._SpecularTextureEnabled = true;
  36945. StandardMaterial._BumpTextureEnabled = true;
  36946. StandardMaterial._LightmapTextureEnabled = true;
  36947. StandardMaterial._RefractionTextureEnabled = true;
  36948. StandardMaterial._ColorGradingTextureEnabled = true;
  36949. StandardMaterial._FresnelEnabled = true;
  36950. __decorate([
  36951. BABYLON.serializeAsTexture("diffuseTexture")
  36952. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36953. __decorate([
  36954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36955. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36956. __decorate([
  36957. BABYLON.serializeAsTexture("ambientTexture")
  36958. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36959. __decorate([
  36960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36961. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36962. __decorate([
  36963. BABYLON.serializeAsTexture("opacityTexture")
  36964. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36965. __decorate([
  36966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36967. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36968. __decorate([
  36969. BABYLON.serializeAsTexture("reflectionTexture")
  36970. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36971. __decorate([
  36972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36973. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36974. __decorate([
  36975. BABYLON.serializeAsTexture("emissiveTexture")
  36976. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36977. __decorate([
  36978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36979. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36980. __decorate([
  36981. BABYLON.serializeAsTexture("specularTexture")
  36982. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36983. __decorate([
  36984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36985. ], StandardMaterial.prototype, "specularTexture", void 0);
  36986. __decorate([
  36987. BABYLON.serializeAsTexture("bumpTexture")
  36988. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36989. __decorate([
  36990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36991. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36992. __decorate([
  36993. BABYLON.serializeAsTexture("lightmapTexture")
  36994. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36995. __decorate([
  36996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36997. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36998. __decorate([
  36999. BABYLON.serializeAsTexture("refractionTexture")
  37000. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37001. __decorate([
  37002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37003. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37004. __decorate([
  37005. BABYLON.serializeAsColor3("ambient")
  37006. ], StandardMaterial.prototype, "ambientColor", void 0);
  37007. __decorate([
  37008. BABYLON.serializeAsColor3("diffuse")
  37009. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37010. __decorate([
  37011. BABYLON.serializeAsColor3("specular")
  37012. ], StandardMaterial.prototype, "specularColor", void 0);
  37013. __decorate([
  37014. BABYLON.serializeAsColor3("emissive")
  37015. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37016. __decorate([
  37017. BABYLON.serialize()
  37018. ], StandardMaterial.prototype, "specularPower", void 0);
  37019. __decorate([
  37020. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37021. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37022. __decorate([
  37023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37024. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37025. __decorate([
  37026. BABYLON.serialize("useEmissiveAsIllumination")
  37027. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37028. __decorate([
  37029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37030. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37031. __decorate([
  37032. BABYLON.serialize("linkEmissiveWithDiffuse")
  37033. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37034. __decorate([
  37035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37036. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37037. __decorate([
  37038. BABYLON.serialize("useSpecularOverAlpha")
  37039. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37040. __decorate([
  37041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37042. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37043. __decorate([
  37044. BABYLON.serialize("useReflectionOverAlpha")
  37045. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37046. __decorate([
  37047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37048. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37049. __decorate([
  37050. BABYLON.serialize("disableLighting")
  37051. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37052. __decorate([
  37053. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37054. ], StandardMaterial.prototype, "disableLighting", void 0);
  37055. __decorate([
  37056. BABYLON.serialize("useParallax")
  37057. ], StandardMaterial.prototype, "_useParallax", void 0);
  37058. __decorate([
  37059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37060. ], StandardMaterial.prototype, "useParallax", void 0);
  37061. __decorate([
  37062. BABYLON.serialize("useParallaxOcclusion")
  37063. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37064. __decorate([
  37065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37066. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37067. __decorate([
  37068. BABYLON.serialize()
  37069. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37070. __decorate([
  37071. BABYLON.serialize("roughness")
  37072. ], StandardMaterial.prototype, "_roughness", void 0);
  37073. __decorate([
  37074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37075. ], StandardMaterial.prototype, "roughness", void 0);
  37076. __decorate([
  37077. BABYLON.serialize()
  37078. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37079. __decorate([
  37080. BABYLON.serialize()
  37081. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37082. __decorate([
  37083. BABYLON.serialize("useLightmapAsShadowmap")
  37084. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37085. __decorate([
  37086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37087. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37088. __decorate([
  37089. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37090. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37091. __decorate([
  37092. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37093. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37094. __decorate([
  37095. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37096. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37097. __decorate([
  37098. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37099. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37100. __decorate([
  37101. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37102. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37103. __decorate([
  37104. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37105. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37106. __decorate([
  37107. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37108. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37109. __decorate([
  37110. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37111. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37112. __decorate([
  37113. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37114. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37115. __decorate([
  37116. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37117. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37118. __decorate([
  37119. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37120. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37121. __decorate([
  37122. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37123. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37124. __decorate([
  37125. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37126. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37127. __decorate([
  37128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37129. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37130. __decorate([
  37131. BABYLON.serialize("maxSimultaneousLights")
  37132. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37133. __decorate([
  37134. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37135. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37136. __decorate([
  37137. BABYLON.serialize("invertNormalMapX")
  37138. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37139. __decorate([
  37140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37141. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37142. __decorate([
  37143. BABYLON.serialize("invertNormalMapY")
  37144. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37145. __decorate([
  37146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37147. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37148. __decorate([
  37149. BABYLON.serialize("twoSidedLighting")
  37150. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37151. __decorate([
  37152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37153. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37154. __decorate([
  37155. BABYLON.serialize()
  37156. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37157. return StandardMaterial;
  37158. }(BABYLON.PushMaterial));
  37159. BABYLON.StandardMaterial = StandardMaterial;
  37160. })(BABYLON || (BABYLON = {}));
  37161. //# sourceMappingURL=babylon.standardMaterial.js.map
  37162. var BABYLON;
  37163. (function (BABYLON) {
  37164. var PBRMaterialDefines = /** @class */ (function (_super) {
  37165. __extends(PBRMaterialDefines, _super);
  37166. function PBRMaterialDefines() {
  37167. var _this = _super.call(this) || this;
  37168. _this.PBR = true;
  37169. _this.MAINUV1 = false;
  37170. _this.MAINUV2 = false;
  37171. _this.UV1 = false;
  37172. _this.UV2 = false;
  37173. _this.ALBEDO = false;
  37174. _this.ALBEDODIRECTUV = 0;
  37175. _this.VERTEXCOLOR = false;
  37176. _this.AMBIENT = false;
  37177. _this.AMBIENTDIRECTUV = 0;
  37178. _this.AMBIENTINGRAYSCALE = false;
  37179. _this.OPACITY = false;
  37180. _this.VERTEXALPHA = false;
  37181. _this.OPACITYDIRECTUV = 0;
  37182. _this.OPACITYRGB = false;
  37183. _this.ALPHATEST = false;
  37184. _this.DEPTHPREPASS = false;
  37185. _this.ALPHABLEND = false;
  37186. _this.ALPHAFROMALBEDO = false;
  37187. _this.ALPHATESTVALUE = 0.5;
  37188. _this.SPECULAROVERALPHA = false;
  37189. _this.RADIANCEOVERALPHA = false;
  37190. _this.ALPHAFRESNEL = false;
  37191. _this.LINEARALPHAFRESNEL = false;
  37192. _this.PREMULTIPLYALPHA = false;
  37193. _this.EMISSIVE = false;
  37194. _this.EMISSIVEDIRECTUV = 0;
  37195. _this.REFLECTIVITY = false;
  37196. _this.REFLECTIVITYDIRECTUV = 0;
  37197. _this.SPECULARTERM = false;
  37198. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37199. _this.MICROSURFACEAUTOMATIC = false;
  37200. _this.LODBASEDMICROSFURACE = false;
  37201. _this.MICROSURFACEMAP = false;
  37202. _this.MICROSURFACEMAPDIRECTUV = 0;
  37203. _this.METALLICWORKFLOW = false;
  37204. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37205. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37206. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37207. _this.AOSTOREINMETALMAPRED = false;
  37208. _this.ENVIRONMENTBRDF = false;
  37209. _this.NORMAL = false;
  37210. _this.TANGENT = false;
  37211. _this.BUMP = false;
  37212. _this.BUMPDIRECTUV = 0;
  37213. _this.PARALLAX = false;
  37214. _this.PARALLAXOCCLUSION = false;
  37215. _this.NORMALXYSCALE = true;
  37216. _this.LIGHTMAP = false;
  37217. _this.LIGHTMAPDIRECTUV = 0;
  37218. _this.USELIGHTMAPASSHADOWMAP = false;
  37219. _this.REFLECTION = false;
  37220. _this.REFLECTIONMAP_3D = false;
  37221. _this.REFLECTIONMAP_SPHERICAL = false;
  37222. _this.REFLECTIONMAP_PLANAR = false;
  37223. _this.REFLECTIONMAP_CUBIC = false;
  37224. _this.REFLECTIONMAP_PROJECTION = false;
  37225. _this.REFLECTIONMAP_SKYBOX = false;
  37226. _this.REFLECTIONMAP_EXPLICIT = false;
  37227. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37228. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37229. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37230. _this.INVERTCUBICMAP = false;
  37231. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37232. _this.USESPHERICALINVERTEX = false;
  37233. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37234. _this.LODINREFLECTIONALPHA = false;
  37235. _this.GAMMAREFLECTION = false;
  37236. _this.RADIANCEOCCLUSION = false;
  37237. _this.HORIZONOCCLUSION = false;
  37238. _this.REFRACTION = false;
  37239. _this.REFRACTIONMAP_3D = false;
  37240. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37241. _this.LODINREFRACTIONALPHA = false;
  37242. _this.GAMMAREFRACTION = false;
  37243. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37244. _this.INSTANCES = false;
  37245. _this.NUM_BONE_INFLUENCERS = 0;
  37246. _this.BonesPerMesh = 0;
  37247. _this.NONUNIFORMSCALING = false;
  37248. _this.MORPHTARGETS = false;
  37249. _this.MORPHTARGETS_NORMAL = false;
  37250. _this.MORPHTARGETS_TANGENT = false;
  37251. _this.NUM_MORPH_INFLUENCERS = 0;
  37252. _this.IMAGEPROCESSING = false;
  37253. _this.VIGNETTE = false;
  37254. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37255. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37256. _this.TONEMAPPING = false;
  37257. _this.CONTRAST = false;
  37258. _this.COLORCURVES = false;
  37259. _this.COLORGRADING = false;
  37260. _this.COLORGRADING3D = false;
  37261. _this.SAMPLER3DGREENDEPTH = false;
  37262. _this.SAMPLER3DBGRMAP = false;
  37263. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37264. _this.EXPOSURE = false;
  37265. _this.USEPHYSICALLIGHTFALLOFF = false;
  37266. _this.TWOSIDEDLIGHTING = false;
  37267. _this.SHADOWFLOAT = false;
  37268. _this.CLIPPLANE = false;
  37269. _this.POINTSIZE = false;
  37270. _this.FOG = false;
  37271. _this.LOGARITHMICDEPTH = false;
  37272. _this.FORCENORMALFORWARD = false;
  37273. _this.rebuild();
  37274. return _this;
  37275. }
  37276. PBRMaterialDefines.prototype.reset = function () {
  37277. _super.prototype.reset.call(this);
  37278. this.ALPHATESTVALUE = 0.5;
  37279. this.PBR = true;
  37280. };
  37281. return PBRMaterialDefines;
  37282. }(BABYLON.MaterialDefines));
  37283. /**
  37284. * The Physically based material base class of BJS.
  37285. *
  37286. * This offers the main features of a standard PBR material.
  37287. * For more information, please refer to the documentation :
  37288. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37289. */
  37290. var PBRBaseMaterial = /** @class */ (function (_super) {
  37291. __extends(PBRBaseMaterial, _super);
  37292. /**
  37293. * Instantiates a new PBRMaterial instance.
  37294. *
  37295. * @param name The material name
  37296. * @param scene The scene the material will be use in.
  37297. */
  37298. function PBRBaseMaterial(name, scene) {
  37299. var _this = _super.call(this, name, scene) || this;
  37300. /**
  37301. * Intensity of the direct lights e.g. the four lights available in your scene.
  37302. * This impacts both the direct diffuse and specular highlights.
  37303. */
  37304. _this._directIntensity = 1.0;
  37305. /**
  37306. * Intensity of the emissive part of the material.
  37307. * This helps controlling the emissive effect without modifying the emissive color.
  37308. */
  37309. _this._emissiveIntensity = 1.0;
  37310. /**
  37311. * Intensity of the environment e.g. how much the environment will light the object
  37312. * either through harmonics for rough material or through the refelction for shiny ones.
  37313. */
  37314. _this._environmentIntensity = 1.0;
  37315. /**
  37316. * This is a special control allowing the reduction of the specular highlights coming from the
  37317. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37318. */
  37319. _this._specularIntensity = 1.0;
  37320. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37321. /**
  37322. * Debug Control allowing disabling the bump map on this material.
  37323. */
  37324. _this._disableBumpMap = false;
  37325. /**
  37326. * AKA Occlusion Texture Intensity in other nomenclature.
  37327. */
  37328. _this._ambientTextureStrength = 1.0;
  37329. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37330. /**
  37331. * AKA Diffuse Color in other nomenclature.
  37332. */
  37333. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37334. /**
  37335. * AKA Specular Color in other nomenclature.
  37336. */
  37337. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37338. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37339. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37340. /**
  37341. * AKA Glossiness in other nomenclature.
  37342. */
  37343. _this._microSurface = 0.9;
  37344. /**
  37345. * source material index of refraction (IOR)' / 'destination material IOR.
  37346. */
  37347. _this._indexOfRefraction = 0.66;
  37348. /**
  37349. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37350. */
  37351. _this._invertRefractionY = false;
  37352. /**
  37353. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37354. * Materials half opaque for instance using refraction could benefit from this control.
  37355. */
  37356. _this._linkRefractionWithTransparency = false;
  37357. _this._useLightmapAsShadowmap = false;
  37358. /**
  37359. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37360. * makes the reflect vector face the model (under horizon).
  37361. */
  37362. _this._useHorizonOcclusion = true;
  37363. /**
  37364. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37365. * too much the area relying on ambient texture to define their ambient occlusion.
  37366. */
  37367. _this._useRadianceOcclusion = true;
  37368. /**
  37369. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37370. */
  37371. _this._useAlphaFromAlbedoTexture = false;
  37372. /**
  37373. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37374. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37375. */
  37376. _this._useSpecularOverAlpha = true;
  37377. /**
  37378. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37379. */
  37380. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37381. /**
  37382. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37383. */
  37384. _this._useRoughnessFromMetallicTextureAlpha = true;
  37385. /**
  37386. * Specifies if the metallic texture contains the roughness information in its green channel.
  37387. */
  37388. _this._useRoughnessFromMetallicTextureGreen = false;
  37389. /**
  37390. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37391. */
  37392. _this._useMetallnessFromMetallicTextureBlue = false;
  37393. /**
  37394. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37395. */
  37396. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37397. /**
  37398. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37399. */
  37400. _this._useAmbientInGrayScale = false;
  37401. /**
  37402. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37403. * The material will try to infer what glossiness each pixel should be.
  37404. */
  37405. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37406. /**
  37407. * BJS is using an harcoded light falloff based on a manually sets up range.
  37408. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37409. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37410. */
  37411. _this._usePhysicalLightFalloff = true;
  37412. /**
  37413. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37414. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37415. */
  37416. _this._useRadianceOverAlpha = true;
  37417. /**
  37418. * Allows using the bump map in parallax mode.
  37419. */
  37420. _this._useParallax = false;
  37421. /**
  37422. * Allows using the bump map in parallax occlusion mode.
  37423. */
  37424. _this._useParallaxOcclusion = false;
  37425. /**
  37426. * Controls the scale bias of the parallax mode.
  37427. */
  37428. _this._parallaxScaleBias = 0.05;
  37429. /**
  37430. * If sets to true, disables all the lights affecting the material.
  37431. */
  37432. _this._disableLighting = false;
  37433. /**
  37434. * Number of Simultaneous lights allowed on the material.
  37435. */
  37436. _this._maxSimultaneousLights = 4;
  37437. /**
  37438. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37439. */
  37440. _this._invertNormalMapX = false;
  37441. /**
  37442. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37443. */
  37444. _this._invertNormalMapY = false;
  37445. /**
  37446. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37447. */
  37448. _this._twoSidedLighting = false;
  37449. /**
  37450. * Defines the alpha limits in alpha test mode.
  37451. */
  37452. _this._alphaCutOff = 0.4;
  37453. /**
  37454. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37455. */
  37456. _this._forceAlphaTest = false;
  37457. /**
  37458. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37459. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37460. */
  37461. _this._useAlphaFresnel = false;
  37462. /**
  37463. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37464. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37465. */
  37466. _this._useLinearAlphaFresnel = false;
  37467. /**
  37468. * The transparency mode of the material.
  37469. */
  37470. _this._transparencyMode = null;
  37471. /**
  37472. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37473. * from cos thetav and roughness:
  37474. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37475. */
  37476. _this._environmentBRDFTexture = null;
  37477. /**
  37478. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37479. */
  37480. _this._forceIrradianceInFragment = false;
  37481. /**
  37482. * Force normal to face away from face.
  37483. */
  37484. _this._forceNormalForward = false;
  37485. /**
  37486. * Force metallic workflow.
  37487. */
  37488. _this._forceMetallicWorkflow = false;
  37489. _this._renderTargets = new BABYLON.SmartArray(16);
  37490. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37491. // Setup the default processing configuration to the scene.
  37492. _this._attachImageProcessingConfiguration(null);
  37493. _this.getRenderTargetTextures = function () {
  37494. _this._renderTargets.reset();
  37495. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37496. _this._renderTargets.push(_this._reflectionTexture);
  37497. }
  37498. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37499. _this._renderTargets.push(_this._refractionTexture);
  37500. }
  37501. return _this._renderTargets;
  37502. };
  37503. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37504. return _this;
  37505. }
  37506. /**
  37507. * Attaches a new image processing configuration to the PBR Material.
  37508. * @param configuration
  37509. */
  37510. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37511. var _this = this;
  37512. if (configuration === this._imageProcessingConfiguration) {
  37513. return;
  37514. }
  37515. // Detaches observer.
  37516. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37517. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37518. }
  37519. // Pick the scene configuration if needed.
  37520. if (!configuration) {
  37521. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37522. }
  37523. else {
  37524. this._imageProcessingConfiguration = configuration;
  37525. }
  37526. // Attaches observer.
  37527. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37528. _this._markAllSubMeshesAsImageProcessingDirty();
  37529. });
  37530. };
  37531. PBRBaseMaterial.prototype.getClassName = function () {
  37532. return "PBRBaseMaterial";
  37533. };
  37534. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37535. get: function () {
  37536. return this._useLogarithmicDepth;
  37537. },
  37538. set: function (value) {
  37539. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37540. },
  37541. enumerable: true,
  37542. configurable: true
  37543. });
  37544. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  37545. /**
  37546. * Gets the current transparency mode.
  37547. */
  37548. get: function () {
  37549. return this._transparencyMode;
  37550. },
  37551. /**
  37552. * Sets the transparency mode of the material.
  37553. */
  37554. set: function (value) {
  37555. if (this._transparencyMode === value) {
  37556. return;
  37557. }
  37558. this._transparencyMode = value;
  37559. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  37560. this._markAllSubMeshesAsTexturesDirty();
  37561. },
  37562. enumerable: true,
  37563. configurable: true
  37564. });
  37565. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  37566. /**
  37567. * Returns true if alpha blending should be disabled.
  37568. */
  37569. get: function () {
  37570. return (this._linkRefractionWithTransparency ||
  37571. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  37572. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. /**
  37578. * Specifies whether or not this material should be rendered in alpha blend mode.
  37579. */
  37580. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37581. if (this._disableAlphaBlending) {
  37582. return false;
  37583. }
  37584. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37585. };
  37586. /**
  37587. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  37588. */
  37589. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  37590. if (this._disableAlphaBlending) {
  37591. return false;
  37592. }
  37593. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  37594. };
  37595. /**
  37596. * Specifies whether or not this material should be rendered in alpha test mode.
  37597. */
  37598. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37599. if (this._forceAlphaTest) {
  37600. return true;
  37601. }
  37602. if (this._linkRefractionWithTransparency) {
  37603. return false;
  37604. }
  37605. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37606. };
  37607. /**
  37608. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  37609. */
  37610. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37611. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37612. };
  37613. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37614. return this._albedoTexture;
  37615. };
  37616. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37617. var _this = this;
  37618. if (subMesh.effect && this.isFrozen) {
  37619. if (this._wasPreviouslyReady) {
  37620. return true;
  37621. }
  37622. }
  37623. if (!subMesh._materialDefines) {
  37624. subMesh._materialDefines = new PBRMaterialDefines();
  37625. }
  37626. var scene = this.getScene();
  37627. var defines = subMesh._materialDefines;
  37628. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37629. if (defines._renderId === scene.getRenderId()) {
  37630. return true;
  37631. }
  37632. }
  37633. var engine = scene.getEngine();
  37634. // Lights
  37635. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37636. defines._needNormals = true;
  37637. // Textures
  37638. if (defines._areTexturesDirty) {
  37639. defines._needUVs = false;
  37640. if (scene.texturesEnabled) {
  37641. if (scene.getEngine().getCaps().textureLOD) {
  37642. defines.LODBASEDMICROSFURACE = true;
  37643. }
  37644. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37645. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37646. return false;
  37647. }
  37648. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37649. }
  37650. else {
  37651. defines.ALBEDO = false;
  37652. }
  37653. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37654. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37655. return false;
  37656. }
  37657. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37658. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37659. }
  37660. else {
  37661. defines.AMBIENT = false;
  37662. }
  37663. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37664. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37665. return false;
  37666. }
  37667. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37668. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37669. }
  37670. else {
  37671. defines.OPACITY = false;
  37672. }
  37673. var reflectionTexture = this._getReflectionTexture();
  37674. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37675. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37676. return false;
  37677. }
  37678. defines.REFLECTION = true;
  37679. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37680. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37681. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37682. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37683. defines.INVERTCUBICMAP = true;
  37684. }
  37685. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37686. switch (reflectionTexture.coordinatesMode) {
  37687. case BABYLON.Texture.CUBIC_MODE:
  37688. case BABYLON.Texture.INVCUBIC_MODE:
  37689. defines.REFLECTIONMAP_CUBIC = true;
  37690. break;
  37691. case BABYLON.Texture.EXPLICIT_MODE:
  37692. defines.REFLECTIONMAP_EXPLICIT = true;
  37693. break;
  37694. case BABYLON.Texture.PLANAR_MODE:
  37695. defines.REFLECTIONMAP_PLANAR = true;
  37696. break;
  37697. case BABYLON.Texture.PROJECTION_MODE:
  37698. defines.REFLECTIONMAP_PROJECTION = true;
  37699. break;
  37700. case BABYLON.Texture.SKYBOX_MODE:
  37701. defines.REFLECTIONMAP_SKYBOX = true;
  37702. break;
  37703. case BABYLON.Texture.SPHERICAL_MODE:
  37704. defines.REFLECTIONMAP_SPHERICAL = true;
  37705. break;
  37706. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37707. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37708. break;
  37709. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37710. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37711. break;
  37712. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37713. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37714. break;
  37715. }
  37716. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37717. if (reflectionTexture.sphericalPolynomial) {
  37718. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37719. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37720. defines.USESPHERICALINVERTEX = false;
  37721. }
  37722. else {
  37723. defines.USESPHERICALINVERTEX = true;
  37724. }
  37725. }
  37726. }
  37727. }
  37728. else {
  37729. defines.REFLECTION = false;
  37730. defines.REFLECTIONMAP_3D = false;
  37731. defines.REFLECTIONMAP_SPHERICAL = false;
  37732. defines.REFLECTIONMAP_PLANAR = false;
  37733. defines.REFLECTIONMAP_CUBIC = false;
  37734. defines.REFLECTIONMAP_PROJECTION = false;
  37735. defines.REFLECTIONMAP_SKYBOX = false;
  37736. defines.REFLECTIONMAP_EXPLICIT = false;
  37737. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37738. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37739. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37740. defines.INVERTCUBICMAP = false;
  37741. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37742. defines.USESPHERICALINVERTEX = false;
  37743. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37744. defines.LODINREFLECTIONALPHA = false;
  37745. defines.GAMMAREFLECTION = false;
  37746. }
  37747. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37748. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37749. return false;
  37750. }
  37751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37752. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37753. }
  37754. else {
  37755. defines.LIGHTMAP = false;
  37756. }
  37757. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37758. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37759. return false;
  37760. }
  37761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37762. }
  37763. else {
  37764. defines.EMISSIVE = false;
  37765. }
  37766. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37767. if (this._metallicTexture) {
  37768. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37769. return false;
  37770. }
  37771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37772. defines.METALLICWORKFLOW = true;
  37773. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37774. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37775. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37776. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37777. }
  37778. else if (this._reflectivityTexture) {
  37779. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37780. return false;
  37781. }
  37782. defines.METALLICWORKFLOW = false;
  37783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37784. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37785. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37786. }
  37787. else {
  37788. defines.METALLICWORKFLOW = false;
  37789. defines.REFLECTIVITY = false;
  37790. }
  37791. if (this._microSurfaceTexture) {
  37792. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37793. return false;
  37794. }
  37795. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37796. }
  37797. else {
  37798. defines.MICROSURFACEMAP = false;
  37799. }
  37800. }
  37801. else {
  37802. defines.REFLECTIVITY = false;
  37803. defines.MICROSURFACEMAP = false;
  37804. }
  37805. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37806. // Bump texure can not be none blocking.
  37807. if (!this._bumpTexture.isReady()) {
  37808. return false;
  37809. }
  37810. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37811. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37812. defines.PARALLAX = true;
  37813. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37814. }
  37815. else {
  37816. defines.PARALLAX = false;
  37817. }
  37818. }
  37819. else {
  37820. defines.BUMP = false;
  37821. }
  37822. var refractionTexture = this._getRefractionTexture();
  37823. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37824. if (!refractionTexture.isReadyOrNotBlocking()) {
  37825. return false;
  37826. }
  37827. defines.REFRACTION = true;
  37828. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37829. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37830. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37831. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37832. if (this._linkRefractionWithTransparency) {
  37833. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37834. }
  37835. }
  37836. else {
  37837. defines.REFRACTION = false;
  37838. }
  37839. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37840. // This is blocking.
  37841. if (!this._environmentBRDFTexture.isReady()) {
  37842. return false;
  37843. }
  37844. defines.ENVIRONMENTBRDF = true;
  37845. }
  37846. else {
  37847. defines.ENVIRONMENTBRDF = false;
  37848. }
  37849. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37850. defines.ALPHAFROMALBEDO = true;
  37851. }
  37852. else {
  37853. defines.ALPHAFROMALBEDO = false;
  37854. }
  37855. }
  37856. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37857. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37858. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37859. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37860. defines.METALLICWORKFLOW = true;
  37861. }
  37862. else {
  37863. defines.METALLICWORKFLOW = false;
  37864. }
  37865. if (!this.backFaceCulling && this._twoSidedLighting) {
  37866. defines.TWOSIDEDLIGHTING = true;
  37867. }
  37868. else {
  37869. defines.TWOSIDEDLIGHTING = false;
  37870. }
  37871. defines.ALPHATESTVALUE = this._alphaCutOff;
  37872. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37873. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37874. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37875. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37876. }
  37877. if (defines._areImageProcessingDirty) {
  37878. if (!this._imageProcessingConfiguration.isReady()) {
  37879. return false;
  37880. }
  37881. this._imageProcessingConfiguration.prepareDefines(defines);
  37882. }
  37883. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37884. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37885. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37886. // Misc.
  37887. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37888. // Values that need to be evaluated on every frame
  37889. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  37890. // Attribs
  37891. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37892. var bufferMesh = null;
  37893. if (mesh instanceof BABYLON.InstancedMesh) {
  37894. bufferMesh = mesh.sourceMesh;
  37895. }
  37896. else if (mesh instanceof BABYLON.Mesh) {
  37897. bufferMesh = mesh;
  37898. }
  37899. if (bufferMesh) {
  37900. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37901. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37902. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37903. var normals = normalVertexBuffer.getData();
  37904. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37905. var strideSize = normalVertexBuffer.getStrideSize();
  37906. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37907. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37908. defines.NORMAL = false;
  37909. }
  37910. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37911. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37912. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37913. var tangents = tangentVertexBuffer.getData();
  37914. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37915. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37916. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37917. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37918. defines.TANGENT = false;
  37919. }
  37920. }
  37921. }
  37922. else {
  37923. if (!scene.getEngine().getCaps().standardDerivatives) {
  37924. bufferMesh.createNormals(true);
  37925. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37926. }
  37927. }
  37928. }
  37929. }
  37930. // Get correct effect
  37931. if (defines.isDirty) {
  37932. defines.markAsProcessed();
  37933. scene.resetCachedMaterial();
  37934. // Fallbacks
  37935. var fallbacks = new BABYLON.EffectFallbacks();
  37936. var fallbackRank = 0;
  37937. if (defines.USESPHERICALINVERTEX) {
  37938. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37939. }
  37940. if (defines.FOG) {
  37941. fallbacks.addFallback(fallbackRank, "FOG");
  37942. }
  37943. if (defines.POINTSIZE) {
  37944. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37945. }
  37946. if (defines.LOGARITHMICDEPTH) {
  37947. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37948. }
  37949. if (defines.PARALLAX) {
  37950. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37951. }
  37952. if (defines.PARALLAXOCCLUSION) {
  37953. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37954. }
  37955. if (defines.ENVIRONMENTBRDF) {
  37956. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37957. }
  37958. if (defines.TANGENT) {
  37959. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37960. }
  37961. if (defines.BUMP) {
  37962. fallbacks.addFallback(fallbackRank++, "BUMP");
  37963. }
  37964. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37965. if (defines.SPECULARTERM) {
  37966. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37967. }
  37968. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37969. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37970. }
  37971. if (defines.LIGHTMAP) {
  37972. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37973. }
  37974. if (defines.NORMAL) {
  37975. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37976. }
  37977. if (defines.AMBIENT) {
  37978. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37979. }
  37980. if (defines.EMISSIVE) {
  37981. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37982. }
  37983. if (defines.VERTEXCOLOR) {
  37984. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37985. }
  37986. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37987. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37988. }
  37989. if (defines.MORPHTARGETS) {
  37990. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37991. }
  37992. //Attributes
  37993. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37994. if (defines.NORMAL) {
  37995. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37996. }
  37997. if (defines.TANGENT) {
  37998. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37999. }
  38000. if (defines.UV1) {
  38001. attribs.push(BABYLON.VertexBuffer.UVKind);
  38002. }
  38003. if (defines.UV2) {
  38004. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38005. }
  38006. if (defines.VERTEXCOLOR) {
  38007. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38008. }
  38009. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38010. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38011. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38012. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38013. "vFogInfos", "vFogColor", "pointSize",
  38014. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38015. "mBones",
  38016. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38017. "vLightingIntensity",
  38018. "logarithmicDepthConstant",
  38019. "vSphericalX", "vSphericalY", "vSphericalZ",
  38020. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38021. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38022. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38023. "vTangentSpaceParams"
  38024. ];
  38025. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38026. "bumpSampler", "lightmapSampler", "opacitySampler",
  38027. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38028. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38029. "microSurfaceSampler", "environmentBrdfSampler"];
  38030. var uniformBuffers = ["Material", "Scene"];
  38031. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38032. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38033. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38034. uniformsNames: uniforms,
  38035. uniformBuffersNames: uniformBuffers,
  38036. samplers: samplers,
  38037. defines: defines,
  38038. maxSimultaneousLights: this._maxSimultaneousLights
  38039. });
  38040. var onCompiled = function (effect) {
  38041. if (_this.onCompiled) {
  38042. _this.onCompiled(effect);
  38043. }
  38044. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38045. };
  38046. var join = defines.toString();
  38047. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38048. attributes: attribs,
  38049. uniformsNames: uniforms,
  38050. uniformBuffersNames: uniformBuffers,
  38051. samplers: samplers,
  38052. defines: join,
  38053. fallbacks: fallbacks,
  38054. onCompiled: onCompiled,
  38055. onError: this.onError,
  38056. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38057. }, engine), defines);
  38058. this.buildUniformLayout();
  38059. }
  38060. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38061. return false;
  38062. }
  38063. defines._renderId = scene.getRenderId();
  38064. this._wasPreviouslyReady = true;
  38065. return true;
  38066. };
  38067. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38068. // Order is important !
  38069. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38070. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38071. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38072. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38073. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38074. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38075. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38076. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38077. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38078. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38079. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38080. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38081. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38082. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38083. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38084. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38085. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38086. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38087. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38088. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38089. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38090. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38091. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38092. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38093. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38094. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38095. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38096. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38097. this._uniformBuffer.addUniform("pointSize", 1);
  38098. this._uniformBuffer.create();
  38099. };
  38100. PBRBaseMaterial.prototype.unbind = function () {
  38101. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38102. this._uniformBuffer.setTexture("reflectionSampler", null);
  38103. }
  38104. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38105. this._uniformBuffer.setTexture("refractionSampler", null);
  38106. }
  38107. _super.prototype.unbind.call(this);
  38108. };
  38109. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38110. this._activeEffect.setMatrix("world", world);
  38111. };
  38112. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38113. var scene = this.getScene();
  38114. var defines = subMesh._materialDefines;
  38115. if (!defines) {
  38116. return;
  38117. }
  38118. var effect = subMesh.effect;
  38119. if (!effect) {
  38120. return;
  38121. }
  38122. this._activeEffect = effect;
  38123. // Matrices
  38124. this.bindOnlyWorldMatrix(world);
  38125. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38126. // Bones
  38127. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38128. var reflectionTexture = null;
  38129. if (mustRebind) {
  38130. this._uniformBuffer.bindToEffect(effect, "Material");
  38131. this.bindViewProjection(effect);
  38132. reflectionTexture = this._getReflectionTexture();
  38133. var refractionTexture = this._getRefractionTexture();
  38134. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38135. // Texture uniforms
  38136. if (scene.texturesEnabled) {
  38137. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38138. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38139. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38140. }
  38141. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38142. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38143. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38144. }
  38145. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38146. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38147. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38148. }
  38149. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38150. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38151. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38152. var polynomials = reflectionTexture.sphericalPolynomial;
  38153. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38154. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38155. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38156. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38157. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38158. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38159. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38160. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38161. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38162. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38163. }
  38164. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38165. }
  38166. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38167. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38168. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38169. }
  38170. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38171. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38172. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38173. }
  38174. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38175. if (this._metallicTexture) {
  38176. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38177. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38178. }
  38179. else if (this._reflectivityTexture) {
  38180. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38181. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38182. }
  38183. if (this._microSurfaceTexture) {
  38184. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38185. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38186. }
  38187. }
  38188. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38189. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38190. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38191. if (scene._mirroredCameraPosition) {
  38192. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38193. }
  38194. else {
  38195. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38196. }
  38197. }
  38198. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38199. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38200. var depth = 1.0;
  38201. if (!refractionTexture.isCube) {
  38202. if (refractionTexture.depth) {
  38203. depth = refractionTexture.depth;
  38204. }
  38205. }
  38206. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38207. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38208. }
  38209. }
  38210. // Point size
  38211. if (this.pointsCloud) {
  38212. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38213. }
  38214. // Colors
  38215. if (defines.METALLICWORKFLOW) {
  38216. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38217. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38218. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38219. }
  38220. else {
  38221. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38222. }
  38223. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38224. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38225. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38226. // Misc
  38227. this._lightingInfos.x = this._directIntensity;
  38228. this._lightingInfos.y = this._emissiveIntensity;
  38229. this._lightingInfos.z = this._environmentIntensity;
  38230. this._lightingInfos.w = this._specularIntensity;
  38231. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38232. }
  38233. // Textures
  38234. if (scene.texturesEnabled) {
  38235. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38236. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38237. }
  38238. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38239. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38240. }
  38241. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38242. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38243. }
  38244. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38245. if (defines.LODBASEDMICROSFURACE) {
  38246. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38247. }
  38248. else {
  38249. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38250. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38251. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38252. }
  38253. }
  38254. if (defines.ENVIRONMENTBRDF) {
  38255. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38256. }
  38257. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38258. if (defines.LODBASEDMICROSFURACE) {
  38259. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38260. }
  38261. else {
  38262. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38263. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38264. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38265. }
  38266. }
  38267. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38268. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38269. }
  38270. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38271. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38272. }
  38273. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38274. if (this._metallicTexture) {
  38275. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38276. }
  38277. else if (this._reflectivityTexture) {
  38278. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38279. }
  38280. if (this._microSurfaceTexture) {
  38281. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38282. }
  38283. }
  38284. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38285. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38286. }
  38287. }
  38288. // Clip plane
  38289. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38290. // Colors
  38291. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38292. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38293. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38294. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38295. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38296. }
  38297. if (mustRebind || !this.isFrozen) {
  38298. // Lights
  38299. if (scene.lightsEnabled && !this._disableLighting) {
  38300. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38301. }
  38302. // View
  38303. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38304. this.bindView(effect);
  38305. }
  38306. // Fog
  38307. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38308. // Morph targets
  38309. if (defines.NUM_MORPH_INFLUENCERS) {
  38310. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38311. }
  38312. // image processing
  38313. this._imageProcessingConfiguration.bind(this._activeEffect);
  38314. // Log. depth
  38315. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38316. }
  38317. this._uniformBuffer.update();
  38318. this._afterBind(mesh);
  38319. };
  38320. PBRBaseMaterial.prototype.getAnimatables = function () {
  38321. var results = [];
  38322. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38323. results.push(this._albedoTexture);
  38324. }
  38325. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38326. results.push(this._ambientTexture);
  38327. }
  38328. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38329. results.push(this._opacityTexture);
  38330. }
  38331. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38332. results.push(this._reflectionTexture);
  38333. }
  38334. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38335. results.push(this._emissiveTexture);
  38336. }
  38337. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38338. results.push(this._metallicTexture);
  38339. }
  38340. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38341. results.push(this._reflectivityTexture);
  38342. }
  38343. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38344. results.push(this._bumpTexture);
  38345. }
  38346. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38347. results.push(this._lightmapTexture);
  38348. }
  38349. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38350. results.push(this._refractionTexture);
  38351. }
  38352. return results;
  38353. };
  38354. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38355. if (this._reflectionTexture) {
  38356. return this._reflectionTexture;
  38357. }
  38358. return this.getScene().environmentTexture;
  38359. };
  38360. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38361. if (this._refractionTexture) {
  38362. return this._refractionTexture;
  38363. }
  38364. if (this._linkRefractionWithTransparency) {
  38365. return this.getScene().environmentTexture;
  38366. }
  38367. return null;
  38368. };
  38369. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38370. if (forceDisposeTextures) {
  38371. if (this._albedoTexture) {
  38372. this._albedoTexture.dispose();
  38373. }
  38374. if (this._ambientTexture) {
  38375. this._ambientTexture.dispose();
  38376. }
  38377. if (this._opacityTexture) {
  38378. this._opacityTexture.dispose();
  38379. }
  38380. if (this._reflectionTexture) {
  38381. this._reflectionTexture.dispose();
  38382. }
  38383. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38384. this._environmentBRDFTexture.dispose();
  38385. }
  38386. if (this._emissiveTexture) {
  38387. this._emissiveTexture.dispose();
  38388. }
  38389. if (this._metallicTexture) {
  38390. this._metallicTexture.dispose();
  38391. }
  38392. if (this._reflectivityTexture) {
  38393. this._reflectivityTexture.dispose();
  38394. }
  38395. if (this._bumpTexture) {
  38396. this._bumpTexture.dispose();
  38397. }
  38398. if (this._lightmapTexture) {
  38399. this._lightmapTexture.dispose();
  38400. }
  38401. if (this._refractionTexture) {
  38402. this._refractionTexture.dispose();
  38403. }
  38404. }
  38405. this._renderTargets.dispose();
  38406. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38407. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38408. }
  38409. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38410. };
  38411. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38412. __decorate([
  38413. BABYLON.serializeAsImageProcessingConfiguration()
  38414. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38415. __decorate([
  38416. BABYLON.serialize()
  38417. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38418. __decorate([
  38419. BABYLON.serialize()
  38420. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38421. return PBRBaseMaterial;
  38422. }(BABYLON.PushMaterial));
  38423. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38424. })(BABYLON || (BABYLON = {}));
  38425. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38426. var BABYLON;
  38427. (function (BABYLON) {
  38428. /**
  38429. * The Physically based simple base material of BJS.
  38430. *
  38431. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38432. * It is used as the base class for both the specGloss and metalRough conventions.
  38433. */
  38434. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38435. __extends(PBRBaseSimpleMaterial, _super);
  38436. /**
  38437. * Instantiates a new PBRMaterial instance.
  38438. *
  38439. * @param name The material name
  38440. * @param scene The scene the material will be use in.
  38441. */
  38442. function PBRBaseSimpleMaterial(name, scene) {
  38443. var _this = _super.call(this, name, scene) || this;
  38444. /**
  38445. * Number of Simultaneous lights allowed on the material.
  38446. */
  38447. _this.maxSimultaneousLights = 4;
  38448. /**
  38449. * If sets to true, disables all the lights affecting the material.
  38450. */
  38451. _this.disableLighting = false;
  38452. /**
  38453. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38454. */
  38455. _this.invertNormalMapX = false;
  38456. /**
  38457. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38458. */
  38459. _this.invertNormalMapY = false;
  38460. /**
  38461. * Emissivie color used to self-illuminate the model.
  38462. */
  38463. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38464. /**
  38465. * Occlusion Channel Strenght.
  38466. */
  38467. _this.occlusionStrength = 1.0;
  38468. _this.useLightmapAsShadowmap = false;
  38469. _this._useAlphaFromAlbedoTexture = true;
  38470. _this._useAmbientInGrayScale = true;
  38471. return _this;
  38472. }
  38473. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38474. /**
  38475. * Gets the current double sided mode.
  38476. */
  38477. get: function () {
  38478. return this._twoSidedLighting;
  38479. },
  38480. /**
  38481. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38482. */
  38483. set: function (value) {
  38484. if (this._twoSidedLighting === value) {
  38485. return;
  38486. }
  38487. this._twoSidedLighting = value;
  38488. this.backFaceCulling = !value;
  38489. this._markAllSubMeshesAsTexturesDirty();
  38490. },
  38491. enumerable: true,
  38492. configurable: true
  38493. });
  38494. /**
  38495. * Return the active textures of the material.
  38496. */
  38497. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38498. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38499. if (this.environmentTexture) {
  38500. activeTextures.push(this.environmentTexture);
  38501. }
  38502. if (this.normalTexture) {
  38503. activeTextures.push(this.normalTexture);
  38504. }
  38505. if (this.emissiveTexture) {
  38506. activeTextures.push(this.emissiveTexture);
  38507. }
  38508. if (this.occlusionTexture) {
  38509. activeTextures.push(this.occlusionTexture);
  38510. }
  38511. if (this.lightmapTexture) {
  38512. activeTextures.push(this.lightmapTexture);
  38513. }
  38514. return activeTextures;
  38515. };
  38516. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  38517. if (_super.prototype.hasTexture.call(this, texture)) {
  38518. return true;
  38519. }
  38520. if (this.lightmapTexture === texture) {
  38521. return true;
  38522. }
  38523. return false;
  38524. };
  38525. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38526. return "PBRBaseSimpleMaterial";
  38527. };
  38528. __decorate([
  38529. BABYLON.serialize(),
  38530. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38531. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38532. __decorate([
  38533. BABYLON.serialize(),
  38534. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38535. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38536. __decorate([
  38537. BABYLON.serializeAsTexture(),
  38538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38539. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38540. __decorate([
  38541. BABYLON.serialize(),
  38542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38543. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38544. __decorate([
  38545. BABYLON.serialize(),
  38546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38547. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38548. __decorate([
  38549. BABYLON.serializeAsTexture(),
  38550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38551. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38552. __decorate([
  38553. BABYLON.serializeAsColor3("emissive"),
  38554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38555. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38556. __decorate([
  38557. BABYLON.serializeAsTexture(),
  38558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38559. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38560. __decorate([
  38561. BABYLON.serialize(),
  38562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38563. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38564. __decorate([
  38565. BABYLON.serializeAsTexture(),
  38566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38567. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38568. __decorate([
  38569. BABYLON.serialize(),
  38570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38571. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38572. __decorate([
  38573. BABYLON.serialize()
  38574. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38575. __decorate([
  38576. BABYLON.serializeAsTexture(),
  38577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38578. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  38579. __decorate([
  38580. BABYLON.serialize(),
  38581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38582. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38583. return PBRBaseSimpleMaterial;
  38584. }(BABYLON.PBRBaseMaterial));
  38585. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38586. })(BABYLON || (BABYLON = {}));
  38587. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38588. var BABYLON;
  38589. (function (BABYLON) {
  38590. /**
  38591. * The Physically based material of BJS.
  38592. *
  38593. * This offers the main features of a standard PBR material.
  38594. * For more information, please refer to the documentation :
  38595. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38596. */
  38597. var PBRMaterial = /** @class */ (function (_super) {
  38598. __extends(PBRMaterial, _super);
  38599. /**
  38600. * Instantiates a new PBRMaterial instance.
  38601. *
  38602. * @param name The material name
  38603. * @param scene The scene the material will be use in.
  38604. */
  38605. function PBRMaterial(name, scene) {
  38606. var _this = _super.call(this, name, scene) || this;
  38607. /**
  38608. * Intensity of the direct lights e.g. the four lights available in your scene.
  38609. * This impacts both the direct diffuse and specular highlights.
  38610. */
  38611. _this.directIntensity = 1.0;
  38612. /**
  38613. * Intensity of the emissive part of the material.
  38614. * This helps controlling the emissive effect without modifying the emissive color.
  38615. */
  38616. _this.emissiveIntensity = 1.0;
  38617. /**
  38618. * Intensity of the environment e.g. how much the environment will light the object
  38619. * either through harmonics for rough material or through the refelction for shiny ones.
  38620. */
  38621. _this.environmentIntensity = 1.0;
  38622. /**
  38623. * This is a special control allowing the reduction of the specular highlights coming from the
  38624. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38625. */
  38626. _this.specularIntensity = 1.0;
  38627. /**
  38628. * Debug Control allowing disabling the bump map on this material.
  38629. */
  38630. _this.disableBumpMap = false;
  38631. /**
  38632. * AKA Occlusion Texture Intensity in other nomenclature.
  38633. */
  38634. _this.ambientTextureStrength = 1.0;
  38635. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38636. /**
  38637. * AKA Diffuse Color in other nomenclature.
  38638. */
  38639. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38640. /**
  38641. * AKA Specular Color in other nomenclature.
  38642. */
  38643. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38644. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38645. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38646. /**
  38647. * AKA Glossiness in other nomenclature.
  38648. */
  38649. _this.microSurface = 1.0;
  38650. /**
  38651. * source material index of refraction (IOR)' / 'destination material IOR.
  38652. */
  38653. _this.indexOfRefraction = 0.66;
  38654. /**
  38655. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38656. */
  38657. _this.invertRefractionY = false;
  38658. /**
  38659. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38660. * Materials half opaque for instance using refraction could benefit from this control.
  38661. */
  38662. _this.linkRefractionWithTransparency = false;
  38663. _this.useLightmapAsShadowmap = false;
  38664. /**
  38665. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38666. */
  38667. _this.useAlphaFromAlbedoTexture = false;
  38668. /**
  38669. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38670. */
  38671. _this.forceAlphaTest = false;
  38672. /**
  38673. * Defines the alpha limits in alpha test mode.
  38674. */
  38675. _this.alphaCutOff = 0.4;
  38676. /**
  38677. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38678. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38679. */
  38680. _this.useSpecularOverAlpha = true;
  38681. /**
  38682. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38683. */
  38684. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38685. /**
  38686. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38687. */
  38688. _this.useRoughnessFromMetallicTextureAlpha = true;
  38689. /**
  38690. * Specifies if the metallic texture contains the roughness information in its green channel.
  38691. */
  38692. _this.useRoughnessFromMetallicTextureGreen = false;
  38693. /**
  38694. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38695. */
  38696. _this.useMetallnessFromMetallicTextureBlue = false;
  38697. /**
  38698. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38699. */
  38700. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38701. /**
  38702. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38703. */
  38704. _this.useAmbientInGrayScale = false;
  38705. /**
  38706. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38707. * The material will try to infer what glossiness each pixel should be.
  38708. */
  38709. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38710. /**
  38711. * BJS is using an harcoded light falloff based on a manually sets up range.
  38712. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38713. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38714. */
  38715. _this.usePhysicalLightFalloff = true;
  38716. /**
  38717. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38718. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38719. */
  38720. _this.useRadianceOverAlpha = true;
  38721. /**
  38722. * Allows using the bump map in parallax mode.
  38723. */
  38724. _this.useParallax = false;
  38725. /**
  38726. * Allows using the bump map in parallax occlusion mode.
  38727. */
  38728. _this.useParallaxOcclusion = false;
  38729. /**
  38730. * Controls the scale bias of the parallax mode.
  38731. */
  38732. _this.parallaxScaleBias = 0.05;
  38733. /**
  38734. * If sets to true, disables all the lights affecting the material.
  38735. */
  38736. _this.disableLighting = false;
  38737. /**
  38738. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38739. */
  38740. _this.forceIrradianceInFragment = false;
  38741. /**
  38742. * Number of Simultaneous lights allowed on the material.
  38743. */
  38744. _this.maxSimultaneousLights = 4;
  38745. /**
  38746. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38747. */
  38748. _this.invertNormalMapX = false;
  38749. /**
  38750. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38751. */
  38752. _this.invertNormalMapY = false;
  38753. /**
  38754. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38755. */
  38756. _this.twoSidedLighting = false;
  38757. /**
  38758. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38759. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38760. */
  38761. _this.useAlphaFresnel = false;
  38762. /**
  38763. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38764. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38765. */
  38766. _this.useLinearAlphaFresnel = false;
  38767. /**
  38768. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38769. * And/Or occlude the blended part.
  38770. */
  38771. _this.environmentBRDFTexture = null;
  38772. /**
  38773. * Force normal to face away from face.
  38774. */
  38775. _this.forceNormalForward = false;
  38776. /**
  38777. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38778. * makes the reflect vector face the model (under horizon).
  38779. */
  38780. _this.useHorizonOcclusion = true;
  38781. /**
  38782. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38783. * too much the area relying on ambient texture to define their ambient occlusion.
  38784. */
  38785. _this.useRadianceOcclusion = true;
  38786. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38787. return _this;
  38788. }
  38789. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38790. /**
  38791. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38792. */
  38793. get: function () {
  38794. return this._PBRMATERIAL_OPAQUE;
  38795. },
  38796. enumerable: true,
  38797. configurable: true
  38798. });
  38799. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38800. /**
  38801. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38802. */
  38803. get: function () {
  38804. return this._PBRMATERIAL_ALPHATEST;
  38805. },
  38806. enumerable: true,
  38807. configurable: true
  38808. });
  38809. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38810. /**
  38811. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38812. */
  38813. get: function () {
  38814. return this._PBRMATERIAL_ALPHABLEND;
  38815. },
  38816. enumerable: true,
  38817. configurable: true
  38818. });
  38819. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38820. /**
  38821. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38822. * They are also discarded below the alpha cutoff threshold to improve performances.
  38823. */
  38824. get: function () {
  38825. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38826. },
  38827. enumerable: true,
  38828. configurable: true
  38829. });
  38830. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38831. /**
  38832. * Gets the image processing configuration used either in this material.
  38833. */
  38834. get: function () {
  38835. return this._imageProcessingConfiguration;
  38836. },
  38837. /**
  38838. * Sets the Default image processing configuration used either in the this material.
  38839. *
  38840. * If sets to null, the scene one is in use.
  38841. */
  38842. set: function (value) {
  38843. this._attachImageProcessingConfiguration(value);
  38844. // Ensure the effect will be rebuilt.
  38845. this._markAllSubMeshesAsTexturesDirty();
  38846. },
  38847. enumerable: true,
  38848. configurable: true
  38849. });
  38850. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38851. /**
  38852. * Gets wether the color curves effect is enabled.
  38853. */
  38854. get: function () {
  38855. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38856. },
  38857. /**
  38858. * Sets wether the color curves effect is enabled.
  38859. */
  38860. set: function (value) {
  38861. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38862. },
  38863. enumerable: true,
  38864. configurable: true
  38865. });
  38866. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38867. /**
  38868. * Gets wether the color grading effect is enabled.
  38869. */
  38870. get: function () {
  38871. return this.imageProcessingConfiguration.colorGradingEnabled;
  38872. },
  38873. /**
  38874. * Gets wether the color grading effect is enabled.
  38875. */
  38876. set: function (value) {
  38877. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38878. },
  38879. enumerable: true,
  38880. configurable: true
  38881. });
  38882. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38883. /**
  38884. * Gets wether tonemapping is enabled or not.
  38885. */
  38886. get: function () {
  38887. return this._imageProcessingConfiguration.toneMappingEnabled;
  38888. },
  38889. /**
  38890. * Sets wether tonemapping is enabled or not
  38891. */
  38892. set: function (value) {
  38893. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38894. },
  38895. enumerable: true,
  38896. configurable: true
  38897. });
  38898. ;
  38899. ;
  38900. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38901. /**
  38902. * The camera exposure used on this material.
  38903. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38904. * This corresponds to a photographic exposure.
  38905. */
  38906. get: function () {
  38907. return this._imageProcessingConfiguration.exposure;
  38908. },
  38909. /**
  38910. * The camera exposure used on this material.
  38911. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38912. * This corresponds to a photographic exposure.
  38913. */
  38914. set: function (value) {
  38915. this._imageProcessingConfiguration.exposure = value;
  38916. },
  38917. enumerable: true,
  38918. configurable: true
  38919. });
  38920. ;
  38921. ;
  38922. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38923. /**
  38924. * Gets The camera contrast used on this material.
  38925. */
  38926. get: function () {
  38927. return this._imageProcessingConfiguration.contrast;
  38928. },
  38929. /**
  38930. * Sets The camera contrast used on this material.
  38931. */
  38932. set: function (value) {
  38933. this._imageProcessingConfiguration.contrast = value;
  38934. },
  38935. enumerable: true,
  38936. configurable: true
  38937. });
  38938. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38939. /**
  38940. * Gets the Color Grading 2D Lookup Texture.
  38941. */
  38942. get: function () {
  38943. return this._imageProcessingConfiguration.colorGradingTexture;
  38944. },
  38945. /**
  38946. * Sets the Color Grading 2D Lookup Texture.
  38947. */
  38948. set: function (value) {
  38949. this._imageProcessingConfiguration.colorGradingTexture = value;
  38950. },
  38951. enumerable: true,
  38952. configurable: true
  38953. });
  38954. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38955. /**
  38956. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38957. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38958. * 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;
  38959. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38960. */
  38961. get: function () {
  38962. return this._imageProcessingConfiguration.colorCurves;
  38963. },
  38964. /**
  38965. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38966. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38967. * 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;
  38968. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38969. */
  38970. set: function (value) {
  38971. this._imageProcessingConfiguration.colorCurves = value;
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. PBRMaterial.prototype.getClassName = function () {
  38977. return "PBRMaterial";
  38978. };
  38979. PBRMaterial.prototype.getActiveTextures = function () {
  38980. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38981. if (this._albedoTexture) {
  38982. activeTextures.push(this._albedoTexture);
  38983. }
  38984. if (this._ambientTexture) {
  38985. activeTextures.push(this._ambientTexture);
  38986. }
  38987. if (this._opacityTexture) {
  38988. activeTextures.push(this._opacityTexture);
  38989. }
  38990. if (this._reflectionTexture) {
  38991. activeTextures.push(this._reflectionTexture);
  38992. }
  38993. if (this._emissiveTexture) {
  38994. activeTextures.push(this._emissiveTexture);
  38995. }
  38996. if (this._reflectivityTexture) {
  38997. activeTextures.push(this._reflectivityTexture);
  38998. }
  38999. if (this._metallicTexture) {
  39000. activeTextures.push(this._metallicTexture);
  39001. }
  39002. if (this._microSurfaceTexture) {
  39003. activeTextures.push(this._microSurfaceTexture);
  39004. }
  39005. if (this._bumpTexture) {
  39006. activeTextures.push(this._bumpTexture);
  39007. }
  39008. if (this._lightmapTexture) {
  39009. activeTextures.push(this._lightmapTexture);
  39010. }
  39011. if (this._refractionTexture) {
  39012. activeTextures.push(this._refractionTexture);
  39013. }
  39014. return activeTextures;
  39015. };
  39016. PBRMaterial.prototype.hasTexture = function (texture) {
  39017. if (_super.prototype.hasTexture.call(this, texture)) {
  39018. return true;
  39019. }
  39020. if (this._albedoTexture === texture) {
  39021. return true;
  39022. }
  39023. if (this._ambientTexture === texture) {
  39024. return true;
  39025. }
  39026. if (this._opacityTexture === texture) {
  39027. return true;
  39028. }
  39029. if (this._reflectionTexture === texture) {
  39030. return true;
  39031. }
  39032. if (this._reflectivityTexture === texture) {
  39033. return true;
  39034. }
  39035. if (this._metallicTexture === texture) {
  39036. return true;
  39037. }
  39038. if (this._microSurfaceTexture === texture) {
  39039. return true;
  39040. }
  39041. if (this._bumpTexture === texture) {
  39042. return true;
  39043. }
  39044. if (this._lightmapTexture === texture) {
  39045. return true;
  39046. }
  39047. if (this._refractionTexture === texture) {
  39048. return true;
  39049. }
  39050. return false;
  39051. };
  39052. PBRMaterial.prototype.clone = function (name) {
  39053. var _this = this;
  39054. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39055. clone.id = name;
  39056. clone.name = name;
  39057. return clone;
  39058. };
  39059. PBRMaterial.prototype.serialize = function () {
  39060. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39061. serializationObject.customType = "BABYLON.PBRMaterial";
  39062. return serializationObject;
  39063. };
  39064. // Statics
  39065. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39066. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39067. };
  39068. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39069. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39070. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39071. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39072. __decorate([
  39073. BABYLON.serialize(),
  39074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39075. ], PBRMaterial.prototype, "directIntensity", void 0);
  39076. __decorate([
  39077. BABYLON.serialize(),
  39078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39079. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39080. __decorate([
  39081. BABYLON.serialize(),
  39082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39083. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39084. __decorate([
  39085. BABYLON.serialize(),
  39086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39087. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39088. __decorate([
  39089. BABYLON.serialize(),
  39090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39091. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39092. __decorate([
  39093. BABYLON.serializeAsTexture(),
  39094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39095. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39096. __decorate([
  39097. BABYLON.serializeAsTexture(),
  39098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39099. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39100. __decorate([
  39101. BABYLON.serialize(),
  39102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39103. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39104. __decorate([
  39105. BABYLON.serializeAsTexture(),
  39106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39107. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39108. __decorate([
  39109. BABYLON.serializeAsTexture(),
  39110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39111. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39112. __decorate([
  39113. BABYLON.serializeAsTexture(),
  39114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39115. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39116. __decorate([
  39117. BABYLON.serializeAsTexture(),
  39118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39119. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39120. __decorate([
  39121. BABYLON.serializeAsTexture(),
  39122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39123. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39124. __decorate([
  39125. BABYLON.serialize(),
  39126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39127. ], PBRMaterial.prototype, "metallic", void 0);
  39128. __decorate([
  39129. BABYLON.serialize(),
  39130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39131. ], PBRMaterial.prototype, "roughness", void 0);
  39132. __decorate([
  39133. BABYLON.serializeAsTexture(),
  39134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39135. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39136. __decorate([
  39137. BABYLON.serializeAsTexture(),
  39138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39139. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39140. __decorate([
  39141. BABYLON.serializeAsTexture(),
  39142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39143. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39144. __decorate([
  39145. BABYLON.serializeAsTexture(),
  39146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39147. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39148. __decorate([
  39149. BABYLON.serializeAsColor3("ambient"),
  39150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39151. ], PBRMaterial.prototype, "ambientColor", void 0);
  39152. __decorate([
  39153. BABYLON.serializeAsColor3("albedo"),
  39154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39155. ], PBRMaterial.prototype, "albedoColor", void 0);
  39156. __decorate([
  39157. BABYLON.serializeAsColor3("reflectivity"),
  39158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39159. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39160. __decorate([
  39161. BABYLON.serializeAsColor3("reflection"),
  39162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39163. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39164. __decorate([
  39165. BABYLON.serializeAsColor3("emissive"),
  39166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39167. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39168. __decorate([
  39169. BABYLON.serialize(),
  39170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39171. ], PBRMaterial.prototype, "microSurface", void 0);
  39172. __decorate([
  39173. BABYLON.serialize(),
  39174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39175. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39176. __decorate([
  39177. BABYLON.serialize(),
  39178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39179. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39180. __decorate([
  39181. BABYLON.serialize(),
  39182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39183. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39184. __decorate([
  39185. BABYLON.serialize(),
  39186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39187. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39188. __decorate([
  39189. BABYLON.serialize(),
  39190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39191. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39192. __decorate([
  39193. BABYLON.serialize(),
  39194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39195. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39196. __decorate([
  39197. BABYLON.serialize(),
  39198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39199. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39200. __decorate([
  39201. BABYLON.serialize(),
  39202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39203. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39204. __decorate([
  39205. BABYLON.serialize(),
  39206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39207. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39208. __decorate([
  39209. BABYLON.serialize(),
  39210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39211. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39212. __decorate([
  39213. BABYLON.serialize(),
  39214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39215. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39216. __decorate([
  39217. BABYLON.serialize(),
  39218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39219. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39220. __decorate([
  39221. BABYLON.serialize(),
  39222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39223. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39224. __decorate([
  39225. BABYLON.serialize(),
  39226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39227. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39228. __decorate([
  39229. BABYLON.serialize(),
  39230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39231. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39232. __decorate([
  39233. BABYLON.serialize(),
  39234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39235. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39236. __decorate([
  39237. BABYLON.serialize(),
  39238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39239. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39240. __decorate([
  39241. BABYLON.serialize(),
  39242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39243. ], PBRMaterial.prototype, "useParallax", void 0);
  39244. __decorate([
  39245. BABYLON.serialize(),
  39246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39247. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39248. __decorate([
  39249. BABYLON.serialize(),
  39250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39251. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39252. __decorate([
  39253. BABYLON.serialize(),
  39254. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39255. ], PBRMaterial.prototype, "disableLighting", void 0);
  39256. __decorate([
  39257. BABYLON.serialize(),
  39258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39259. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39260. __decorate([
  39261. BABYLON.serialize(),
  39262. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39263. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39264. __decorate([
  39265. BABYLON.serialize(),
  39266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39267. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39268. __decorate([
  39269. BABYLON.serialize(),
  39270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39271. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39272. __decorate([
  39273. BABYLON.serialize(),
  39274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39275. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39276. __decorate([
  39277. BABYLON.serialize(),
  39278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39279. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39280. __decorate([
  39281. BABYLON.serialize(),
  39282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39283. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39284. __decorate([
  39285. BABYLON.serializeAsTexture(),
  39286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39287. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39288. __decorate([
  39289. BABYLON.serialize(),
  39290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39291. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39292. __decorate([
  39293. BABYLON.serialize(),
  39294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39295. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39296. __decorate([
  39297. BABYLON.serialize(),
  39298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39299. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39300. return PBRMaterial;
  39301. }(BABYLON.PBRBaseMaterial));
  39302. BABYLON.PBRMaterial = PBRMaterial;
  39303. })(BABYLON || (BABYLON = {}));
  39304. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39305. var BABYLON;
  39306. (function (BABYLON) {
  39307. /**
  39308. * The PBR material of BJS following the metal roughness convention.
  39309. *
  39310. * This fits to the PBR convention in the GLTF definition:
  39311. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39312. */
  39313. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39314. __extends(PBRMetallicRoughnessMaterial, _super);
  39315. /**
  39316. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39317. *
  39318. * @param name The material name
  39319. * @param scene The scene the material will be use in.
  39320. */
  39321. function PBRMetallicRoughnessMaterial(name, scene) {
  39322. var _this = _super.call(this, name, scene) || this;
  39323. _this._useRoughnessFromMetallicTextureAlpha = false;
  39324. _this._useRoughnessFromMetallicTextureGreen = true;
  39325. _this._useMetallnessFromMetallicTextureBlue = true;
  39326. _this._forceMetallicWorkflow = true;
  39327. return _this;
  39328. }
  39329. /**
  39330. * Return the currrent class name of the material.
  39331. */
  39332. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39333. return "PBRMetallicRoughnessMaterial";
  39334. };
  39335. /**
  39336. * Return the active textures of the material.
  39337. */
  39338. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39339. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39340. if (this.baseTexture) {
  39341. activeTextures.push(this.baseTexture);
  39342. }
  39343. if (this.metallicRoughnessTexture) {
  39344. activeTextures.push(this.metallicRoughnessTexture);
  39345. }
  39346. return activeTextures;
  39347. };
  39348. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39349. if (_super.prototype.hasTexture.call(this, texture)) {
  39350. return true;
  39351. }
  39352. if (this.baseTexture === texture) {
  39353. return true;
  39354. }
  39355. if (this.metallicRoughnessTexture === texture) {
  39356. return true;
  39357. }
  39358. return false;
  39359. };
  39360. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39361. var _this = this;
  39362. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39363. clone.id = name;
  39364. clone.name = name;
  39365. return clone;
  39366. };
  39367. /**
  39368. * Serialize the material to a parsable JSON object.
  39369. */
  39370. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39371. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39372. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39373. return serializationObject;
  39374. };
  39375. /**
  39376. * Parses a JSON object correponding to the serialize function.
  39377. */
  39378. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39379. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39380. };
  39381. __decorate([
  39382. BABYLON.serializeAsColor3(),
  39383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39384. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39385. __decorate([
  39386. BABYLON.serializeAsTexture(),
  39387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39388. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39389. __decorate([
  39390. BABYLON.serialize(),
  39391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39392. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39393. __decorate([
  39394. BABYLON.serialize(),
  39395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39396. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39397. __decorate([
  39398. BABYLON.serializeAsTexture(),
  39399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39400. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39401. return PBRMetallicRoughnessMaterial;
  39402. }(BABYLON.PBRBaseSimpleMaterial));
  39403. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39404. })(BABYLON || (BABYLON = {}));
  39405. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39406. var BABYLON;
  39407. (function (BABYLON) {
  39408. /**
  39409. * The PBR material of BJS following the specular glossiness convention.
  39410. *
  39411. * This fits to the PBR convention in the GLTF definition:
  39412. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39413. */
  39414. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39415. __extends(PBRSpecularGlossinessMaterial, _super);
  39416. /**
  39417. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39418. *
  39419. * @param name The material name
  39420. * @param scene The scene the material will be use in.
  39421. */
  39422. function PBRSpecularGlossinessMaterial(name, scene) {
  39423. var _this = _super.call(this, name, scene) || this;
  39424. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39425. return _this;
  39426. }
  39427. /**
  39428. * Return the currrent class name of the material.
  39429. */
  39430. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39431. return "PBRSpecularGlossinessMaterial";
  39432. };
  39433. /**
  39434. * Return the active textures of the material.
  39435. */
  39436. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39437. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39438. if (this.diffuseTexture) {
  39439. activeTextures.push(this.diffuseTexture);
  39440. }
  39441. if (this.specularGlossinessTexture) {
  39442. activeTextures.push(this.specularGlossinessTexture);
  39443. }
  39444. return activeTextures;
  39445. };
  39446. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39447. if (_super.prototype.hasTexture.call(this, texture)) {
  39448. return true;
  39449. }
  39450. if (this.diffuseTexture === texture) {
  39451. return true;
  39452. }
  39453. if (this.specularGlossinessTexture === texture) {
  39454. return true;
  39455. }
  39456. return false;
  39457. };
  39458. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39459. var _this = this;
  39460. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39461. clone.id = name;
  39462. clone.name = name;
  39463. return clone;
  39464. };
  39465. /**
  39466. * Serialize the material to a parsable JSON object.
  39467. */
  39468. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39469. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39470. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39471. return serializationObject;
  39472. };
  39473. /**
  39474. * Parses a JSON object correponding to the serialize function.
  39475. */
  39476. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39477. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39478. };
  39479. __decorate([
  39480. BABYLON.serializeAsColor3("diffuse"),
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39482. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39483. __decorate([
  39484. BABYLON.serializeAsTexture(),
  39485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39486. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39487. __decorate([
  39488. BABYLON.serializeAsColor3("specular"),
  39489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39490. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39491. __decorate([
  39492. BABYLON.serialize(),
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39494. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39495. __decorate([
  39496. BABYLON.serializeAsTexture(),
  39497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39498. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39499. return PBRSpecularGlossinessMaterial;
  39500. }(BABYLON.PBRBaseSimpleMaterial));
  39501. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39502. })(BABYLON || (BABYLON = {}));
  39503. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39504. var BABYLON;
  39505. (function (BABYLON) {
  39506. BABYLON.CameraInputTypes = {};
  39507. var CameraInputsManager = /** @class */ (function () {
  39508. function CameraInputsManager(camera) {
  39509. this.attached = {};
  39510. this.camera = camera;
  39511. this.checkInputs = function () { };
  39512. }
  39513. /**
  39514. * Add an input method to a camera.
  39515. * builtin inputs example: camera.inputs.addGamepad();
  39516. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  39517. * @param input camera input method
  39518. */
  39519. CameraInputsManager.prototype.add = function (input) {
  39520. var type = input.getSimpleName();
  39521. if (this.attached[type]) {
  39522. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  39523. return;
  39524. }
  39525. this.attached[type] = input;
  39526. input.camera = this.camera;
  39527. //for checkInputs, we are dynamically creating a function
  39528. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  39529. if (input.checkInputs) {
  39530. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39531. }
  39532. if (this.attachedElement) {
  39533. input.attachControl(this.attachedElement);
  39534. }
  39535. };
  39536. /**
  39537. * Remove a specific input method from a camera
  39538. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  39539. * @param inputToRemove camera input method
  39540. */
  39541. CameraInputsManager.prototype.remove = function (inputToRemove) {
  39542. for (var cam in this.attached) {
  39543. var input = this.attached[cam];
  39544. if (input === inputToRemove) {
  39545. input.detachControl(this.attachedElement);
  39546. input.camera = null;
  39547. delete this.attached[cam];
  39548. this.rebuildInputCheck();
  39549. }
  39550. }
  39551. };
  39552. CameraInputsManager.prototype.removeByType = function (inputType) {
  39553. for (var cam in this.attached) {
  39554. var input = this.attached[cam];
  39555. if (input.getClassName() === inputType) {
  39556. input.detachControl(this.attachedElement);
  39557. input.camera = null;
  39558. delete this.attached[cam];
  39559. this.rebuildInputCheck();
  39560. }
  39561. }
  39562. };
  39563. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  39564. var current = this.checkInputs;
  39565. return function () {
  39566. current();
  39567. fn();
  39568. };
  39569. };
  39570. CameraInputsManager.prototype.attachInput = function (input) {
  39571. if (this.attachedElement) {
  39572. input.attachControl(this.attachedElement, this.noPreventDefault);
  39573. }
  39574. };
  39575. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  39576. if (noPreventDefault === void 0) { noPreventDefault = false; }
  39577. if (this.attachedElement) {
  39578. return;
  39579. }
  39580. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  39581. this.attachedElement = element;
  39582. this.noPreventDefault = noPreventDefault;
  39583. for (var cam in this.attached) {
  39584. this.attached[cam].attachControl(element, noPreventDefault);
  39585. }
  39586. };
  39587. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  39588. if (disconnect === void 0) { disconnect = false; }
  39589. if (this.attachedElement !== element) {
  39590. return;
  39591. }
  39592. for (var cam in this.attached) {
  39593. this.attached[cam].detachControl(element);
  39594. if (disconnect) {
  39595. this.attached[cam].camera = null;
  39596. }
  39597. }
  39598. this.attachedElement = null;
  39599. };
  39600. CameraInputsManager.prototype.rebuildInputCheck = function () {
  39601. this.checkInputs = function () { };
  39602. for (var cam in this.attached) {
  39603. var input = this.attached[cam];
  39604. if (input.checkInputs) {
  39605. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39606. }
  39607. }
  39608. };
  39609. /**
  39610. * Remove all attached input methods from a camera
  39611. */
  39612. CameraInputsManager.prototype.clear = function () {
  39613. if (this.attachedElement) {
  39614. this.detachElement(this.attachedElement, true);
  39615. }
  39616. this.attached = {};
  39617. this.attachedElement = null;
  39618. this.checkInputs = function () { };
  39619. };
  39620. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  39621. var inputs = {};
  39622. for (var cam in this.attached) {
  39623. var input = this.attached[cam];
  39624. var res = BABYLON.SerializationHelper.Serialize(input);
  39625. inputs[input.getClassName()] = res;
  39626. }
  39627. serializedCamera.inputsmgr = inputs;
  39628. };
  39629. CameraInputsManager.prototype.parse = function (parsedCamera) {
  39630. var parsedInputs = parsedCamera.inputsmgr;
  39631. if (parsedInputs) {
  39632. this.clear();
  39633. for (var n in parsedInputs) {
  39634. var construct = BABYLON.CameraInputTypes[n];
  39635. if (construct) {
  39636. var parsedinput = parsedInputs[n];
  39637. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  39638. this.add(input);
  39639. }
  39640. }
  39641. }
  39642. else {
  39643. //2016-03-08 this part is for managing backward compatibility
  39644. for (var n in this.attached) {
  39645. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  39646. if (construct) {
  39647. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  39648. this.remove(this.attached[n]);
  39649. this.add(input);
  39650. }
  39651. }
  39652. }
  39653. };
  39654. return CameraInputsManager;
  39655. }());
  39656. BABYLON.CameraInputsManager = CameraInputsManager;
  39657. })(BABYLON || (BABYLON = {}));
  39658. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  39659. var BABYLON;
  39660. (function (BABYLON) {
  39661. var TargetCamera = /** @class */ (function (_super) {
  39662. __extends(TargetCamera, _super);
  39663. function TargetCamera(name, position, scene) {
  39664. var _this = _super.call(this, name, position, scene) || this;
  39665. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39666. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  39667. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  39668. _this.speed = 2.0;
  39669. _this.noRotationConstraint = false;
  39670. _this.lockedTarget = null;
  39671. _this._currentTarget = BABYLON.Vector3.Zero();
  39672. _this._viewMatrix = BABYLON.Matrix.Zero();
  39673. _this._camMatrix = BABYLON.Matrix.Zero();
  39674. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  39675. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  39676. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  39677. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  39678. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  39679. _this._lookAtTemp = BABYLON.Matrix.Zero();
  39680. _this._tempMatrix = BABYLON.Matrix.Zero();
  39681. return _this;
  39682. }
  39683. TargetCamera.prototype.getFrontPosition = function (distance) {
  39684. this.getWorldMatrix();
  39685. var direction = this.getTarget().subtract(this.position);
  39686. direction.normalize();
  39687. direction.scaleInPlace(distance);
  39688. return this.globalPosition.add(direction);
  39689. };
  39690. TargetCamera.prototype._getLockedTargetPosition = function () {
  39691. if (!this.lockedTarget) {
  39692. return null;
  39693. }
  39694. if (this.lockedTarget.absolutePosition) {
  39695. this.lockedTarget.computeWorldMatrix();
  39696. }
  39697. return this.lockedTarget.absolutePosition || this.lockedTarget;
  39698. };
  39699. TargetCamera.prototype.storeState = function () {
  39700. this._storedPosition = this.position.clone();
  39701. this._storedRotation = this.rotation.clone();
  39702. if (this.rotationQuaternion) {
  39703. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  39704. }
  39705. return _super.prototype.storeState.call(this);
  39706. };
  39707. /**
  39708. * Restored camera state. You must call storeState() first
  39709. */
  39710. TargetCamera.prototype._restoreStateValues = function () {
  39711. if (!_super.prototype._restoreStateValues.call(this)) {
  39712. return false;
  39713. }
  39714. this.position = this._storedPosition.clone();
  39715. this.rotation = this._storedRotation.clone();
  39716. if (this.rotationQuaternion) {
  39717. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39718. }
  39719. this.cameraDirection.copyFromFloats(0, 0, 0);
  39720. this.cameraRotation.copyFromFloats(0, 0);
  39721. return true;
  39722. };
  39723. // Cache
  39724. TargetCamera.prototype._initCache = function () {
  39725. _super.prototype._initCache.call(this);
  39726. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39727. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39728. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39729. };
  39730. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39731. if (!ignoreParentClass) {
  39732. _super.prototype._updateCache.call(this);
  39733. }
  39734. var lockedTargetPosition = this._getLockedTargetPosition();
  39735. if (!lockedTargetPosition) {
  39736. this._cache.lockedTarget = null;
  39737. }
  39738. else {
  39739. if (!this._cache.lockedTarget) {
  39740. this._cache.lockedTarget = lockedTargetPosition.clone();
  39741. }
  39742. else {
  39743. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39744. }
  39745. }
  39746. this._cache.rotation.copyFrom(this.rotation);
  39747. if (this.rotationQuaternion)
  39748. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39749. };
  39750. // Synchronized
  39751. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39752. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39753. return false;
  39754. }
  39755. var lockedTargetPosition = this._getLockedTargetPosition();
  39756. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39757. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39758. };
  39759. // Methods
  39760. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39761. var engine = this.getEngine();
  39762. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39763. };
  39764. // Target
  39765. TargetCamera.prototype.setTarget = function (target) {
  39766. this.upVector.normalize();
  39767. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39768. this._camMatrix.invert();
  39769. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39770. var vDir = target.subtract(this.position);
  39771. if (vDir.x >= 0.0) {
  39772. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39773. }
  39774. else {
  39775. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39776. }
  39777. this.rotation.z = 0;
  39778. if (isNaN(this.rotation.x)) {
  39779. this.rotation.x = 0;
  39780. }
  39781. if (isNaN(this.rotation.y)) {
  39782. this.rotation.y = 0;
  39783. }
  39784. if (isNaN(this.rotation.z)) {
  39785. this.rotation.z = 0;
  39786. }
  39787. if (this.rotationQuaternion) {
  39788. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39789. }
  39790. };
  39791. /**
  39792. * Return the current target position of the camera. This value is expressed in local space.
  39793. */
  39794. TargetCamera.prototype.getTarget = function () {
  39795. return this._currentTarget;
  39796. };
  39797. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39798. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39799. };
  39800. TargetCamera.prototype._updatePosition = function () {
  39801. if (this.parent) {
  39802. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39803. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39804. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39805. return;
  39806. }
  39807. this.position.addInPlace(this.cameraDirection);
  39808. };
  39809. TargetCamera.prototype._checkInputs = function () {
  39810. var needToMove = this._decideIfNeedsToMove();
  39811. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39812. // Move
  39813. if (needToMove) {
  39814. this._updatePosition();
  39815. }
  39816. // Rotate
  39817. if (needToRotate) {
  39818. this.rotation.x += this.cameraRotation.x;
  39819. this.rotation.y += this.cameraRotation.y;
  39820. //rotate, if quaternion is set and rotation was used
  39821. if (this.rotationQuaternion) {
  39822. var len = this.rotation.lengthSquared();
  39823. if (len) {
  39824. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39825. }
  39826. }
  39827. if (!this.noRotationConstraint) {
  39828. var limit = (Math.PI / 2) * 0.95;
  39829. if (this.rotation.x > limit)
  39830. this.rotation.x = limit;
  39831. if (this.rotation.x < -limit)
  39832. this.rotation.x = -limit;
  39833. }
  39834. }
  39835. // Inertia
  39836. if (needToMove) {
  39837. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39838. this.cameraDirection.x = 0;
  39839. }
  39840. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39841. this.cameraDirection.y = 0;
  39842. }
  39843. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39844. this.cameraDirection.z = 0;
  39845. }
  39846. this.cameraDirection.scaleInPlace(this.inertia);
  39847. }
  39848. if (needToRotate) {
  39849. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39850. this.cameraRotation.x = 0;
  39851. }
  39852. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39853. this.cameraRotation.y = 0;
  39854. }
  39855. this.cameraRotation.scaleInPlace(this.inertia);
  39856. }
  39857. _super.prototype._checkInputs.call(this);
  39858. };
  39859. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39860. if (this.rotationQuaternion) {
  39861. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39862. }
  39863. else {
  39864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39865. }
  39866. //update the up vector!
  39867. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39868. };
  39869. TargetCamera.prototype._getViewMatrix = function () {
  39870. if (this.lockedTarget) {
  39871. this.setTarget(this._getLockedTargetPosition());
  39872. }
  39873. // Compute
  39874. this._updateCameraRotationMatrix();
  39875. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39876. // Computing target and final matrix
  39877. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39878. if (this.getScene().useRightHandedSystem) {
  39879. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39880. }
  39881. else {
  39882. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39883. }
  39884. return this._viewMatrix;
  39885. };
  39886. /**
  39887. * @override
  39888. * Override Camera.createRigCamera
  39889. */
  39890. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39891. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39892. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39893. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39894. if (!this.rotationQuaternion) {
  39895. this.rotationQuaternion = new BABYLON.Quaternion();
  39896. }
  39897. rigCamera._cameraRigParams = {};
  39898. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39899. }
  39900. return rigCamera;
  39901. }
  39902. return null;
  39903. };
  39904. /**
  39905. * @override
  39906. * Override Camera._updateRigCameras
  39907. */
  39908. TargetCamera.prototype._updateRigCameras = function () {
  39909. var camLeft = this._rigCameras[0];
  39910. var camRight = this._rigCameras[1];
  39911. switch (this.cameraRigMode) {
  39912. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39916. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39917. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39918. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39919. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39920. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39921. camLeft.setTarget(this.getTarget());
  39922. camRight.setTarget(this.getTarget());
  39923. break;
  39924. case BABYLON.Camera.RIG_MODE_VR:
  39925. if (camLeft.rotationQuaternion) {
  39926. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39927. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39928. }
  39929. else {
  39930. camLeft.rotation.copyFrom(this.rotation);
  39931. camRight.rotation.copyFrom(this.rotation);
  39932. }
  39933. camLeft.position.copyFrom(this.position);
  39934. camRight.position.copyFrom(this.position);
  39935. break;
  39936. }
  39937. _super.prototype._updateRigCameras.call(this);
  39938. };
  39939. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39940. if (!this._rigCamTransformMatrix) {
  39941. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39942. }
  39943. var target = this.getTarget();
  39944. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39945. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39946. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39947. };
  39948. TargetCamera.prototype.getClassName = function () {
  39949. return "TargetCamera";
  39950. };
  39951. __decorate([
  39952. BABYLON.serializeAsVector3()
  39953. ], TargetCamera.prototype, "rotation", void 0);
  39954. __decorate([
  39955. BABYLON.serialize()
  39956. ], TargetCamera.prototype, "speed", void 0);
  39957. __decorate([
  39958. BABYLON.serializeAsMeshReference("lockedTargetId")
  39959. ], TargetCamera.prototype, "lockedTarget", void 0);
  39960. return TargetCamera;
  39961. }(BABYLON.Camera));
  39962. BABYLON.TargetCamera = TargetCamera;
  39963. })(BABYLON || (BABYLON = {}));
  39964. //# sourceMappingURL=babylon.targetCamera.js.map
  39965. var BABYLON;
  39966. (function (BABYLON) {
  39967. var FreeCameraMouseInput = /** @class */ (function () {
  39968. function FreeCameraMouseInput(touchEnabled) {
  39969. if (touchEnabled === void 0) { touchEnabled = true; }
  39970. this.touchEnabled = touchEnabled;
  39971. this.buttons = [0, 1, 2];
  39972. this.angularSensibility = 2000.0;
  39973. this.previousPosition = null;
  39974. }
  39975. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39976. var _this = this;
  39977. var engine = this.camera.getEngine();
  39978. if (!this._pointerInput) {
  39979. this._pointerInput = function (p, s) {
  39980. var evt = p.event;
  39981. if (engine.isInVRExclusivePointerMode) {
  39982. return;
  39983. }
  39984. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39985. return;
  39986. }
  39987. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39988. return;
  39989. }
  39990. var srcElement = (evt.srcElement || evt.target);
  39991. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39992. try {
  39993. srcElement.setPointerCapture(evt.pointerId);
  39994. }
  39995. catch (e) {
  39996. //Nothing to do with the error. Execution will continue.
  39997. }
  39998. _this.previousPosition = {
  39999. x: evt.clientX,
  40000. y: evt.clientY
  40001. };
  40002. if (!noPreventDefault) {
  40003. evt.preventDefault();
  40004. element.focus();
  40005. }
  40006. }
  40007. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40008. try {
  40009. srcElement.releasePointerCapture(evt.pointerId);
  40010. }
  40011. catch (e) {
  40012. //Nothing to do with the error.
  40013. }
  40014. _this.previousPosition = null;
  40015. if (!noPreventDefault) {
  40016. evt.preventDefault();
  40017. }
  40018. }
  40019. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40020. if (!_this.previousPosition || engine.isPointerLock) {
  40021. return;
  40022. }
  40023. var offsetX = evt.clientX - _this.previousPosition.x;
  40024. var offsetY = evt.clientY - _this.previousPosition.y;
  40025. if (_this.camera.getScene().useRightHandedSystem) {
  40026. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40027. }
  40028. else {
  40029. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40030. }
  40031. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40032. _this.previousPosition = {
  40033. x: evt.clientX,
  40034. y: evt.clientY
  40035. };
  40036. if (!noPreventDefault) {
  40037. evt.preventDefault();
  40038. }
  40039. }
  40040. };
  40041. }
  40042. this._onMouseMove = function (evt) {
  40043. if (!engine.isPointerLock) {
  40044. return;
  40045. }
  40046. if (engine.isInVRExclusivePointerMode) {
  40047. return;
  40048. }
  40049. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40050. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40051. if (_this.camera.getScene().useRightHandedSystem) {
  40052. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40053. }
  40054. else {
  40055. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40056. }
  40057. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40058. _this.previousPosition = null;
  40059. if (!noPreventDefault) {
  40060. evt.preventDefault();
  40061. }
  40062. };
  40063. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40064. element.addEventListener("mousemove", this._onMouseMove, false);
  40065. };
  40066. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40067. if (this._observer && element) {
  40068. this.camera.getScene().onPointerObservable.remove(this._observer);
  40069. if (this._onMouseMove) {
  40070. element.removeEventListener("mousemove", this._onMouseMove);
  40071. }
  40072. this._observer = null;
  40073. this._onMouseMove = null;
  40074. this.previousPosition = null;
  40075. }
  40076. };
  40077. FreeCameraMouseInput.prototype.getClassName = function () {
  40078. return "FreeCameraMouseInput";
  40079. };
  40080. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40081. return "mouse";
  40082. };
  40083. __decorate([
  40084. BABYLON.serialize()
  40085. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40086. __decorate([
  40087. BABYLON.serialize()
  40088. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40089. return FreeCameraMouseInput;
  40090. }());
  40091. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40092. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40093. })(BABYLON || (BABYLON = {}));
  40094. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40095. var BABYLON;
  40096. (function (BABYLON) {
  40097. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40098. function FreeCameraKeyboardMoveInput() {
  40099. this._keys = new Array();
  40100. this.keysUp = [38];
  40101. this.keysDown = [40];
  40102. this.keysLeft = [37];
  40103. this.keysRight = [39];
  40104. }
  40105. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40106. var _this = this;
  40107. if (this._onCanvasBlurObserver) {
  40108. return;
  40109. }
  40110. this._scene = this.camera.getScene();
  40111. this._engine = this._scene.getEngine();
  40112. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40113. _this._keys = [];
  40114. });
  40115. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40116. var evt = info.event;
  40117. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40118. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40119. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40120. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40121. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40122. var index = _this._keys.indexOf(evt.keyCode);
  40123. if (index === -1) {
  40124. _this._keys.push(evt.keyCode);
  40125. }
  40126. if (!noPreventDefault) {
  40127. evt.preventDefault();
  40128. }
  40129. }
  40130. }
  40131. else {
  40132. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40133. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40134. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40135. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40136. var index = _this._keys.indexOf(evt.keyCode);
  40137. if (index >= 0) {
  40138. _this._keys.splice(index, 1);
  40139. }
  40140. if (!noPreventDefault) {
  40141. evt.preventDefault();
  40142. }
  40143. }
  40144. }
  40145. });
  40146. };
  40147. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40148. if (this._scene) {
  40149. if (this._onKeyboardObserver) {
  40150. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40151. }
  40152. if (this._onCanvasBlurObserver) {
  40153. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40154. }
  40155. this._onKeyboardObserver = null;
  40156. this._onCanvasBlurObserver = null;
  40157. }
  40158. this._keys = [];
  40159. };
  40160. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40161. if (this._onKeyboardObserver) {
  40162. var camera = this.camera;
  40163. // Keyboard
  40164. for (var index = 0; index < this._keys.length; index++) {
  40165. var keyCode = this._keys[index];
  40166. var speed = camera._computeLocalCameraSpeed();
  40167. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40168. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40169. }
  40170. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40171. camera._localDirection.copyFromFloats(0, 0, speed);
  40172. }
  40173. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40174. camera._localDirection.copyFromFloats(speed, 0, 0);
  40175. }
  40176. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40177. camera._localDirection.copyFromFloats(0, 0, -speed);
  40178. }
  40179. if (camera.getScene().useRightHandedSystem) {
  40180. camera._localDirection.z *= -1;
  40181. }
  40182. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40183. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40184. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40185. }
  40186. }
  40187. };
  40188. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40189. return "FreeCameraKeyboardMoveInput";
  40190. };
  40191. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40192. this._keys = [];
  40193. };
  40194. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40195. return "keyboard";
  40196. };
  40197. __decorate([
  40198. BABYLON.serialize()
  40199. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40200. __decorate([
  40201. BABYLON.serialize()
  40202. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40203. __decorate([
  40204. BABYLON.serialize()
  40205. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40206. __decorate([
  40207. BABYLON.serialize()
  40208. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40209. return FreeCameraKeyboardMoveInput;
  40210. }());
  40211. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40212. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40213. })(BABYLON || (BABYLON = {}));
  40214. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40215. var BABYLON;
  40216. (function (BABYLON) {
  40217. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40218. __extends(FreeCameraInputsManager, _super);
  40219. function FreeCameraInputsManager(camera) {
  40220. return _super.call(this, camera) || this;
  40221. }
  40222. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40223. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40224. return this;
  40225. };
  40226. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40227. if (touchEnabled === void 0) { touchEnabled = true; }
  40228. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40229. return this;
  40230. };
  40231. FreeCameraInputsManager.prototype.addGamepad = function () {
  40232. this.add(new BABYLON.FreeCameraGamepadInput());
  40233. return this;
  40234. };
  40235. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40236. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40237. return this;
  40238. };
  40239. FreeCameraInputsManager.prototype.addTouch = function () {
  40240. this.add(new BABYLON.FreeCameraTouchInput());
  40241. return this;
  40242. };
  40243. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40244. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40245. return this;
  40246. };
  40247. return FreeCameraInputsManager;
  40248. }(BABYLON.CameraInputsManager));
  40249. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40250. })(BABYLON || (BABYLON = {}));
  40251. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40252. var BABYLON;
  40253. (function (BABYLON) {
  40254. var FreeCamera = /** @class */ (function (_super) {
  40255. __extends(FreeCamera, _super);
  40256. function FreeCamera(name, position, scene) {
  40257. var _this = _super.call(this, name, position, scene) || this;
  40258. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40259. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40260. _this.checkCollisions = false;
  40261. _this.applyGravity = false;
  40262. _this._needMoveForGravity = false;
  40263. _this._oldPosition = BABYLON.Vector3.Zero();
  40264. _this._diffPosition = BABYLON.Vector3.Zero();
  40265. _this._newPosition = BABYLON.Vector3.Zero();
  40266. // Collisions
  40267. _this._collisionMask = -1;
  40268. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40269. if (collidedMesh === void 0) { collidedMesh = null; }
  40270. //TODO move this to the collision coordinator!
  40271. if (_this.getScene().workerCollisions)
  40272. newPosition.multiplyInPlace(_this._collider._radius);
  40273. var updatePosition = function (newPos) {
  40274. _this._newPosition.copyFrom(newPos);
  40275. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40276. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40277. _this.position.addInPlace(_this._diffPosition);
  40278. if (_this.onCollide && collidedMesh) {
  40279. _this.onCollide(collidedMesh);
  40280. }
  40281. }
  40282. };
  40283. updatePosition(newPosition);
  40284. };
  40285. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40286. _this.inputs.addKeyboard().addMouse();
  40287. return _this;
  40288. }
  40289. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40290. //-- begin properties for backward compatibility for inputs
  40291. /**
  40292. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40293. * Higher values reduce sensitivity.
  40294. */
  40295. get: function () {
  40296. var mouse = this.inputs.attached["mouse"];
  40297. if (mouse)
  40298. return mouse.angularSensibility;
  40299. return 0;
  40300. },
  40301. /**
  40302. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40303. * Higher values reduce sensitivity.
  40304. */
  40305. set: function (value) {
  40306. var mouse = this.inputs.attached["mouse"];
  40307. if (mouse)
  40308. mouse.angularSensibility = value;
  40309. },
  40310. enumerable: true,
  40311. configurable: true
  40312. });
  40313. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40314. get: function () {
  40315. var keyboard = this.inputs.attached["keyboard"];
  40316. if (keyboard)
  40317. return keyboard.keysUp;
  40318. return [];
  40319. },
  40320. set: function (value) {
  40321. var keyboard = this.inputs.attached["keyboard"];
  40322. if (keyboard)
  40323. keyboard.keysUp = value;
  40324. },
  40325. enumerable: true,
  40326. configurable: true
  40327. });
  40328. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40329. get: function () {
  40330. var keyboard = this.inputs.attached["keyboard"];
  40331. if (keyboard)
  40332. return keyboard.keysDown;
  40333. return [];
  40334. },
  40335. set: function (value) {
  40336. var keyboard = this.inputs.attached["keyboard"];
  40337. if (keyboard)
  40338. keyboard.keysDown = value;
  40339. },
  40340. enumerable: true,
  40341. configurable: true
  40342. });
  40343. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40344. get: function () {
  40345. var keyboard = this.inputs.attached["keyboard"];
  40346. if (keyboard)
  40347. return keyboard.keysLeft;
  40348. return [];
  40349. },
  40350. set: function (value) {
  40351. var keyboard = this.inputs.attached["keyboard"];
  40352. if (keyboard)
  40353. keyboard.keysLeft = value;
  40354. },
  40355. enumerable: true,
  40356. configurable: true
  40357. });
  40358. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40359. get: function () {
  40360. var keyboard = this.inputs.attached["keyboard"];
  40361. if (keyboard)
  40362. return keyboard.keysRight;
  40363. return [];
  40364. },
  40365. set: function (value) {
  40366. var keyboard = this.inputs.attached["keyboard"];
  40367. if (keyboard)
  40368. keyboard.keysRight = value;
  40369. },
  40370. enumerable: true,
  40371. configurable: true
  40372. });
  40373. // Controls
  40374. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40375. this.inputs.attachElement(element, noPreventDefault);
  40376. };
  40377. FreeCamera.prototype.detachControl = function (element) {
  40378. this.inputs.detachElement(element);
  40379. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40380. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40381. };
  40382. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40383. get: function () {
  40384. return this._collisionMask;
  40385. },
  40386. set: function (mask) {
  40387. this._collisionMask = !isNaN(mask) ? mask : -1;
  40388. },
  40389. enumerable: true,
  40390. configurable: true
  40391. });
  40392. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40393. var globalPosition;
  40394. if (this.parent) {
  40395. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40396. }
  40397. else {
  40398. globalPosition = this.position;
  40399. }
  40400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40401. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40402. if (!this._collider) {
  40403. this._collider = new BABYLON.Collider();
  40404. }
  40405. this._collider._radius = this.ellipsoid;
  40406. this._collider.collisionMask = this._collisionMask;
  40407. //no need for clone, as long as gravity is not on.
  40408. var actualDisplacement = displacement;
  40409. //add gravity to the direction to prevent the dual-collision checking
  40410. if (this.applyGravity) {
  40411. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40412. actualDisplacement = displacement.add(this.getScene().gravity);
  40413. }
  40414. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40415. };
  40416. FreeCamera.prototype._checkInputs = function () {
  40417. if (!this._localDirection) {
  40418. this._localDirection = BABYLON.Vector3.Zero();
  40419. this._transformedDirection = BABYLON.Vector3.Zero();
  40420. }
  40421. this.inputs.checkInputs();
  40422. _super.prototype._checkInputs.call(this);
  40423. };
  40424. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40425. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40426. };
  40427. FreeCamera.prototype._updatePosition = function () {
  40428. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40429. this._collideWithWorld(this.cameraDirection);
  40430. }
  40431. else {
  40432. _super.prototype._updatePosition.call(this);
  40433. }
  40434. };
  40435. FreeCamera.prototype.dispose = function () {
  40436. this.inputs.clear();
  40437. _super.prototype.dispose.call(this);
  40438. };
  40439. FreeCamera.prototype.getClassName = function () {
  40440. return "FreeCamera";
  40441. };
  40442. __decorate([
  40443. BABYLON.serializeAsVector3()
  40444. ], FreeCamera.prototype, "ellipsoid", void 0);
  40445. __decorate([
  40446. BABYLON.serializeAsVector3()
  40447. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40448. __decorate([
  40449. BABYLON.serialize()
  40450. ], FreeCamera.prototype, "checkCollisions", void 0);
  40451. __decorate([
  40452. BABYLON.serialize()
  40453. ], FreeCamera.prototype, "applyGravity", void 0);
  40454. return FreeCamera;
  40455. }(BABYLON.TargetCamera));
  40456. BABYLON.FreeCamera = FreeCamera;
  40457. })(BABYLON || (BABYLON = {}));
  40458. //# sourceMappingURL=babylon.freeCamera.js.map
  40459. var BABYLON;
  40460. (function (BABYLON) {
  40461. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40462. function ArcRotateCameraKeyboardMoveInput() {
  40463. this._keys = new Array();
  40464. this.keysUp = [38];
  40465. this.keysDown = [40];
  40466. this.keysLeft = [37];
  40467. this.keysRight = [39];
  40468. this.keysReset = [220];
  40469. this.panningSensibility = 50.0;
  40470. this.zoomingSensibility = 25.0;
  40471. this.useAltToZoom = true;
  40472. }
  40473. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40474. var _this = this;
  40475. if (this._onCanvasBlurObserver) {
  40476. return;
  40477. }
  40478. this._scene = this.camera.getScene();
  40479. this._engine = this._scene.getEngine();
  40480. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40481. _this._keys = [];
  40482. });
  40483. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40484. var evt = info.event;
  40485. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40486. _this._ctrlPressed = evt.ctrlKey;
  40487. _this._altPressed = evt.altKey;
  40488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40491. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40492. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40493. var index = _this._keys.indexOf(evt.keyCode);
  40494. if (index === -1) {
  40495. _this._keys.push(evt.keyCode);
  40496. }
  40497. if (evt.preventDefault) {
  40498. if (!noPreventDefault) {
  40499. evt.preventDefault();
  40500. }
  40501. }
  40502. }
  40503. }
  40504. else {
  40505. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40506. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40507. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40508. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40509. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40510. var index = _this._keys.indexOf(evt.keyCode);
  40511. if (index >= 0) {
  40512. _this._keys.splice(index, 1);
  40513. }
  40514. if (evt.preventDefault) {
  40515. if (!noPreventDefault) {
  40516. evt.preventDefault();
  40517. }
  40518. }
  40519. }
  40520. }
  40521. });
  40522. };
  40523. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40524. if (this._scene) {
  40525. if (this._onKeyboardObserver) {
  40526. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40527. }
  40528. if (this._onCanvasBlurObserver) {
  40529. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40530. }
  40531. this._onKeyboardObserver = null;
  40532. this._onCanvasBlurObserver = null;
  40533. }
  40534. this._keys = [];
  40535. };
  40536. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40537. if (this._onKeyboardObserver) {
  40538. var camera = this.camera;
  40539. for (var index = 0; index < this._keys.length; index++) {
  40540. var keyCode = this._keys[index];
  40541. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40542. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40543. camera.inertialPanningX -= 1 / this.panningSensibility;
  40544. }
  40545. else {
  40546. camera.inertialAlphaOffset -= 0.01;
  40547. }
  40548. }
  40549. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40550. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40551. camera.inertialPanningY += 1 / this.panningSensibility;
  40552. }
  40553. else if (this._altPressed && this.useAltToZoom) {
  40554. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  40555. }
  40556. else {
  40557. camera.inertialBetaOffset -= 0.01;
  40558. }
  40559. }
  40560. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40561. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40562. camera.inertialPanningX += 1 / this.panningSensibility;
  40563. }
  40564. else {
  40565. camera.inertialAlphaOffset += 0.01;
  40566. }
  40567. }
  40568. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40569. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40570. camera.inertialPanningY -= 1 / this.panningSensibility;
  40571. }
  40572. else if (this._altPressed && this.useAltToZoom) {
  40573. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  40574. }
  40575. else {
  40576. camera.inertialBetaOffset += 0.01;
  40577. }
  40578. }
  40579. else if (this.keysReset.indexOf(keyCode) !== -1) {
  40580. camera.restoreState();
  40581. }
  40582. }
  40583. }
  40584. };
  40585. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  40586. return "ArcRotateCameraKeyboardMoveInput";
  40587. };
  40588. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40589. return "keyboard";
  40590. };
  40591. __decorate([
  40592. BABYLON.serialize()
  40593. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40594. __decorate([
  40595. BABYLON.serialize()
  40596. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40597. __decorate([
  40598. BABYLON.serialize()
  40599. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40600. __decorate([
  40601. BABYLON.serialize()
  40602. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40603. __decorate([
  40604. BABYLON.serialize()
  40605. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  40606. __decorate([
  40607. BABYLON.serialize()
  40608. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  40609. __decorate([
  40610. BABYLON.serialize()
  40611. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  40612. __decorate([
  40613. BABYLON.serialize()
  40614. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  40615. return ArcRotateCameraKeyboardMoveInput;
  40616. }());
  40617. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  40618. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  40619. })(BABYLON || (BABYLON = {}));
  40620. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  40621. var BABYLON;
  40622. (function (BABYLON) {
  40623. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  40624. function ArcRotateCameraMouseWheelInput() {
  40625. this.wheelPrecision = 3.0;
  40626. /**
  40627. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  40628. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  40629. */
  40630. this.wheelDeltaPercentage = 0;
  40631. }
  40632. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  40633. var _this = this;
  40634. this._wheel = function (p, s) {
  40635. //sanity check - this should be a PointerWheel event.
  40636. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  40637. return;
  40638. var event = p.event;
  40639. var delta = 0;
  40640. if (event.wheelDelta) {
  40641. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  40642. }
  40643. else if (event.detail) {
  40644. delta = -event.detail / _this.wheelPrecision;
  40645. }
  40646. if (delta)
  40647. _this.camera.inertialRadiusOffset += delta;
  40648. if (event.preventDefault) {
  40649. if (!noPreventDefault) {
  40650. event.preventDefault();
  40651. }
  40652. }
  40653. };
  40654. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  40655. };
  40656. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  40657. if (this._observer && element) {
  40658. this.camera.getScene().onPointerObservable.remove(this._observer);
  40659. this._observer = null;
  40660. this._wheel = null;
  40661. }
  40662. };
  40663. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  40664. return "ArcRotateCameraMouseWheelInput";
  40665. };
  40666. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  40667. return "mousewheel";
  40668. };
  40669. __decorate([
  40670. BABYLON.serialize()
  40671. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  40672. __decorate([
  40673. BABYLON.serialize()
  40674. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  40675. return ArcRotateCameraMouseWheelInput;
  40676. }());
  40677. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  40678. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  40679. })(BABYLON || (BABYLON = {}));
  40680. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  40681. var BABYLON;
  40682. (function (BABYLON) {
  40683. var ArcRotateCameraPointersInput = /** @class */ (function () {
  40684. function ArcRotateCameraPointersInput() {
  40685. this.buttons = [0, 1, 2];
  40686. this.angularSensibilityX = 1000.0;
  40687. this.angularSensibilityY = 1000.0;
  40688. this.pinchPrecision = 12.0;
  40689. /**
  40690. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  40691. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  40692. */
  40693. this.pinchDeltaPercentage = 0;
  40694. this.panningSensibility = 1000.0;
  40695. this.multiTouchPanning = true;
  40696. this.multiTouchPanAndZoom = true;
  40697. this._isPanClick = false;
  40698. this.pinchInwards = true;
  40699. }
  40700. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  40701. var _this = this;
  40702. var engine = this.camera.getEngine();
  40703. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  40704. var pointA = null;
  40705. var pointB = null;
  40706. var previousPinchSquaredDistance = 0;
  40707. var initialDistance = 0;
  40708. var twoFingerActivityCount = 0;
  40709. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  40710. this._pointerInput = function (p, s) {
  40711. var evt = p.event;
  40712. var isTouch = p.event.pointerType === "touch";
  40713. if (engine.isInVRExclusivePointerMode) {
  40714. return;
  40715. }
  40716. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40717. return;
  40718. }
  40719. var srcElement = (evt.srcElement || evt.target);
  40720. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40721. try {
  40722. srcElement.setPointerCapture(evt.pointerId);
  40723. }
  40724. catch (e) {
  40725. //Nothing to do with the error. Execution will continue.
  40726. }
  40727. // Manage panning with pan button click
  40728. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40729. // manage pointers
  40730. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40731. if (pointA === null) {
  40732. pointA = cacheSoloPointer;
  40733. }
  40734. else if (pointB === null) {
  40735. pointB = cacheSoloPointer;
  40736. }
  40737. if (!noPreventDefault) {
  40738. evt.preventDefault();
  40739. element.focus();
  40740. }
  40741. }
  40742. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40743. _this.camera.restoreState();
  40744. }
  40745. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40746. try {
  40747. srcElement.releasePointerCapture(evt.pointerId);
  40748. }
  40749. catch (e) {
  40750. //Nothing to do with the error.
  40751. }
  40752. cacheSoloPointer = null;
  40753. previousPinchSquaredDistance = 0;
  40754. previousMultiTouchPanPosition.isPaning = false;
  40755. previousMultiTouchPanPosition.isPinching = false;
  40756. twoFingerActivityCount = 0;
  40757. initialDistance = 0;
  40758. if (!isTouch) {
  40759. pointB = null; // Mouse and pen are mono pointer
  40760. }
  40761. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40762. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40763. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40764. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40765. if (engine.badOS) {
  40766. pointA = pointB = null;
  40767. }
  40768. else {
  40769. //only remove the impacted pointer in case of multitouch allowing on most
  40770. //platforms switching from rotate to zoom and pan seamlessly.
  40771. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40772. pointA = pointB;
  40773. pointB = null;
  40774. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40775. }
  40776. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40777. pointB = null;
  40778. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40779. }
  40780. else {
  40781. pointA = pointB = null;
  40782. }
  40783. }
  40784. if (!noPreventDefault) {
  40785. evt.preventDefault();
  40786. }
  40787. }
  40788. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40789. if (!noPreventDefault) {
  40790. evt.preventDefault();
  40791. }
  40792. // One button down
  40793. if (pointA && pointB === null && cacheSoloPointer) {
  40794. if (_this.panningSensibility !== 0 &&
  40795. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40796. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40797. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40798. }
  40799. else {
  40800. var offsetX = evt.clientX - cacheSoloPointer.x;
  40801. var offsetY = evt.clientY - cacheSoloPointer.y;
  40802. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40803. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40804. }
  40805. cacheSoloPointer.x = evt.clientX;
  40806. cacheSoloPointer.y = evt.clientY;
  40807. }
  40808. else if (pointA && pointB) {
  40809. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40810. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40811. ed.x = evt.clientX;
  40812. ed.y = evt.clientY;
  40813. var direction = _this.pinchInwards ? 1 : -1;
  40814. var distX = pointA.x - pointB.x;
  40815. var distY = pointA.y - pointB.y;
  40816. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40817. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40818. if (previousPinchSquaredDistance === 0) {
  40819. initialDistance = pinchDistance;
  40820. previousPinchSquaredDistance = pinchSquaredDistance;
  40821. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40822. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40823. return;
  40824. }
  40825. if (_this.multiTouchPanAndZoom) {
  40826. if (_this.pinchDeltaPercentage) {
  40827. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40828. }
  40829. else {
  40830. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40831. (_this.pinchPrecision *
  40832. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40833. direction);
  40834. }
  40835. if (_this.panningSensibility !== 0) {
  40836. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40837. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40838. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40839. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40840. previousMultiTouchPanPosition.x = pointersCenterX;
  40841. previousMultiTouchPanPosition.y = pointersCenterY;
  40842. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40843. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40844. }
  40845. }
  40846. else {
  40847. twoFingerActivityCount++;
  40848. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40849. if (_this.pinchDeltaPercentage) {
  40850. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40851. }
  40852. else {
  40853. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40854. (_this.pinchPrecision *
  40855. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40856. direction);
  40857. }
  40858. previousMultiTouchPanPosition.isPaning = false;
  40859. previousMultiTouchPanPosition.isPinching = true;
  40860. }
  40861. else {
  40862. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40863. if (!previousMultiTouchPanPosition.isPaning) {
  40864. previousMultiTouchPanPosition.isPaning = true;
  40865. previousMultiTouchPanPosition.isPinching = false;
  40866. previousMultiTouchPanPosition.x = ed.x;
  40867. previousMultiTouchPanPosition.y = ed.y;
  40868. return;
  40869. }
  40870. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40871. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40872. }
  40873. }
  40874. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40875. previousMultiTouchPanPosition.x = ed.x;
  40876. previousMultiTouchPanPosition.y = ed.y;
  40877. }
  40878. }
  40879. previousPinchSquaredDistance = pinchSquaredDistance;
  40880. }
  40881. }
  40882. };
  40883. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40884. this._onContextMenu = function (evt) {
  40885. evt.preventDefault();
  40886. };
  40887. if (!this.camera._useCtrlForPanning) {
  40888. element.addEventListener("contextmenu", this._onContextMenu, false);
  40889. }
  40890. this._onLostFocus = function () {
  40891. //this._keys = [];
  40892. pointA = pointB = null;
  40893. previousPinchSquaredDistance = 0;
  40894. previousMultiTouchPanPosition.isPaning = false;
  40895. previousMultiTouchPanPosition.isPinching = false;
  40896. twoFingerActivityCount = 0;
  40897. cacheSoloPointer = null;
  40898. initialDistance = 0;
  40899. };
  40900. this._onMouseMove = function (evt) {
  40901. if (!engine.isPointerLock) {
  40902. return;
  40903. }
  40904. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40905. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40906. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40907. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40908. if (!noPreventDefault) {
  40909. evt.preventDefault();
  40910. }
  40911. };
  40912. this._onGestureStart = function (e) {
  40913. if (window.MSGesture === undefined) {
  40914. return;
  40915. }
  40916. if (!_this._MSGestureHandler) {
  40917. _this._MSGestureHandler = new MSGesture();
  40918. _this._MSGestureHandler.target = element;
  40919. }
  40920. _this._MSGestureHandler.addPointer(e.pointerId);
  40921. };
  40922. this._onGesture = function (e) {
  40923. _this.camera.radius *= e.scale;
  40924. if (e.preventDefault) {
  40925. if (!noPreventDefault) {
  40926. e.stopPropagation();
  40927. e.preventDefault();
  40928. }
  40929. }
  40930. };
  40931. element.addEventListener("mousemove", this._onMouseMove, false);
  40932. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40933. element.addEventListener("MSGestureChange", this._onGesture, false);
  40934. BABYLON.Tools.RegisterTopRootEvents([
  40935. { name: "blur", handler: this._onLostFocus }
  40936. ]);
  40937. };
  40938. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40939. if (this._onLostFocus) {
  40940. BABYLON.Tools.UnregisterTopRootEvents([
  40941. { name: "blur", handler: this._onLostFocus }
  40942. ]);
  40943. }
  40944. if (element && this._observer) {
  40945. this.camera.getScene().onPointerObservable.remove(this._observer);
  40946. this._observer = null;
  40947. if (this._onContextMenu) {
  40948. element.removeEventListener("contextmenu", this._onContextMenu);
  40949. }
  40950. if (this._onMouseMove) {
  40951. element.removeEventListener("mousemove", this._onMouseMove);
  40952. }
  40953. if (this._onGestureStart) {
  40954. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40955. }
  40956. if (this._onGesture) {
  40957. element.removeEventListener("MSGestureChange", this._onGesture);
  40958. }
  40959. this._isPanClick = false;
  40960. this.pinchInwards = true;
  40961. this._onMouseMove = null;
  40962. this._onGestureStart = null;
  40963. this._onGesture = null;
  40964. this._MSGestureHandler = null;
  40965. this._onLostFocus = null;
  40966. this._onContextMenu = null;
  40967. }
  40968. };
  40969. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40970. return "ArcRotateCameraPointersInput";
  40971. };
  40972. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40973. return "pointers";
  40974. };
  40975. __decorate([
  40976. BABYLON.serialize()
  40977. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40978. __decorate([
  40979. BABYLON.serialize()
  40980. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40981. __decorate([
  40982. BABYLON.serialize()
  40983. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40984. __decorate([
  40985. BABYLON.serialize()
  40986. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40987. __decorate([
  40988. BABYLON.serialize()
  40989. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40990. __decorate([
  40991. BABYLON.serialize()
  40992. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40993. __decorate([
  40994. BABYLON.serialize()
  40995. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40996. __decorate([
  40997. BABYLON.serialize()
  40998. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40999. return ArcRotateCameraPointersInput;
  41000. }());
  41001. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41002. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41003. })(BABYLON || (BABYLON = {}));
  41004. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41005. var BABYLON;
  41006. (function (BABYLON) {
  41007. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41008. __extends(ArcRotateCameraInputsManager, _super);
  41009. function ArcRotateCameraInputsManager(camera) {
  41010. return _super.call(this, camera) || this;
  41011. }
  41012. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41013. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41014. return this;
  41015. };
  41016. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41017. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41018. return this;
  41019. };
  41020. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41021. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41022. return this;
  41023. };
  41024. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41025. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41026. return this;
  41027. };
  41028. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41029. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41030. return this;
  41031. };
  41032. return ArcRotateCameraInputsManager;
  41033. }(BABYLON.CameraInputsManager));
  41034. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41035. })(BABYLON || (BABYLON = {}));
  41036. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41037. var BABYLON;
  41038. (function (BABYLON) {
  41039. var ArcRotateCamera = /** @class */ (function (_super) {
  41040. __extends(ArcRotateCamera, _super);
  41041. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41042. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41043. _this.inertialAlphaOffset = 0;
  41044. _this.inertialBetaOffset = 0;
  41045. _this.inertialRadiusOffset = 0;
  41046. _this.lowerAlphaLimit = null;
  41047. _this.upperAlphaLimit = null;
  41048. _this.lowerBetaLimit = 0.01;
  41049. _this.upperBetaLimit = Math.PI;
  41050. _this.lowerRadiusLimit = null;
  41051. _this.upperRadiusLimit = null;
  41052. _this.inertialPanningX = 0;
  41053. _this.inertialPanningY = 0;
  41054. _this.pinchToPanMaxDistance = 20;
  41055. _this.panningDistanceLimit = null;
  41056. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41057. _this.panningInertia = 0.9;
  41058. //-- end properties for backward compatibility for inputs
  41059. _this.zoomOnFactor = 1;
  41060. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41061. _this.allowUpsideDown = true;
  41062. _this._viewMatrix = new BABYLON.Matrix();
  41063. // Panning
  41064. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41065. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41066. _this.checkCollisions = false;
  41067. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41068. _this._previousPosition = BABYLON.Vector3.Zero();
  41069. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41070. _this._newPosition = BABYLON.Vector3.Zero();
  41071. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41072. if (collidedMesh === void 0) { collidedMesh = null; }
  41073. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41074. newPosition.multiplyInPlace(_this._collider._radius);
  41075. }
  41076. if (!collidedMesh) {
  41077. _this._previousPosition.copyFrom(_this.position);
  41078. }
  41079. else {
  41080. _this.setPosition(newPosition);
  41081. if (_this.onCollide) {
  41082. _this.onCollide(collidedMesh);
  41083. }
  41084. }
  41085. // Recompute because of constraints
  41086. var cosa = Math.cos(_this.alpha);
  41087. var sina = Math.sin(_this.alpha);
  41088. var cosb = Math.cos(_this.beta);
  41089. var sinb = Math.sin(_this.beta);
  41090. if (sinb === 0) {
  41091. sinb = 0.0001;
  41092. }
  41093. var target = _this._getTargetPosition();
  41094. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41095. _this.position.copyFrom(_this._newPosition);
  41096. var up = _this.upVector;
  41097. if (_this.allowUpsideDown && _this.beta < 0) {
  41098. up = up.clone();
  41099. up = up.negate();
  41100. }
  41101. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41102. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41103. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41104. _this._collisionTriggered = false;
  41105. };
  41106. _this._target = BABYLON.Vector3.Zero();
  41107. if (target) {
  41108. _this.setTarget(target);
  41109. }
  41110. _this.alpha = alpha;
  41111. _this.beta = beta;
  41112. _this.radius = radius;
  41113. _this.getViewMatrix();
  41114. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41115. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41116. return _this;
  41117. }
  41118. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41119. get: function () {
  41120. return this._target;
  41121. },
  41122. set: function (value) {
  41123. this.setTarget(value);
  41124. },
  41125. enumerable: true,
  41126. configurable: true
  41127. });
  41128. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41129. //-- begin properties for backward compatibility for inputs
  41130. get: function () {
  41131. var pointers = this.inputs.attached["pointers"];
  41132. if (pointers)
  41133. return pointers.angularSensibilityX;
  41134. return 0;
  41135. },
  41136. set: function (value) {
  41137. var pointers = this.inputs.attached["pointers"];
  41138. if (pointers) {
  41139. pointers.angularSensibilityX = value;
  41140. }
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41146. get: function () {
  41147. var pointers = this.inputs.attached["pointers"];
  41148. if (pointers)
  41149. return pointers.angularSensibilityY;
  41150. return 0;
  41151. },
  41152. set: function (value) {
  41153. var pointers = this.inputs.attached["pointers"];
  41154. if (pointers) {
  41155. pointers.angularSensibilityY = value;
  41156. }
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41162. get: function () {
  41163. var pointers = this.inputs.attached["pointers"];
  41164. if (pointers)
  41165. return pointers.pinchPrecision;
  41166. return 0;
  41167. },
  41168. set: function (value) {
  41169. var pointers = this.inputs.attached["pointers"];
  41170. if (pointers) {
  41171. pointers.pinchPrecision = value;
  41172. }
  41173. },
  41174. enumerable: true,
  41175. configurable: true
  41176. });
  41177. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41178. get: function () {
  41179. var pointers = this.inputs.attached["pointers"];
  41180. if (pointers)
  41181. return pointers.pinchDeltaPercentage;
  41182. return 0;
  41183. },
  41184. set: function (value) {
  41185. var pointers = this.inputs.attached["pointers"];
  41186. if (pointers) {
  41187. pointers.pinchDeltaPercentage = value;
  41188. }
  41189. },
  41190. enumerable: true,
  41191. configurable: true
  41192. });
  41193. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41194. get: function () {
  41195. var pointers = this.inputs.attached["pointers"];
  41196. if (pointers)
  41197. return pointers.panningSensibility;
  41198. return 0;
  41199. },
  41200. set: function (value) {
  41201. var pointers = this.inputs.attached["pointers"];
  41202. if (pointers) {
  41203. pointers.panningSensibility = value;
  41204. }
  41205. },
  41206. enumerable: true,
  41207. configurable: true
  41208. });
  41209. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41210. get: function () {
  41211. var keyboard = this.inputs.attached["keyboard"];
  41212. if (keyboard)
  41213. return keyboard.keysUp;
  41214. return [];
  41215. },
  41216. set: function (value) {
  41217. var keyboard = this.inputs.attached["keyboard"];
  41218. if (keyboard)
  41219. keyboard.keysUp = value;
  41220. },
  41221. enumerable: true,
  41222. configurable: true
  41223. });
  41224. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41225. get: function () {
  41226. var keyboard = this.inputs.attached["keyboard"];
  41227. if (keyboard)
  41228. return keyboard.keysDown;
  41229. return [];
  41230. },
  41231. set: function (value) {
  41232. var keyboard = this.inputs.attached["keyboard"];
  41233. if (keyboard)
  41234. keyboard.keysDown = value;
  41235. },
  41236. enumerable: true,
  41237. configurable: true
  41238. });
  41239. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41240. get: function () {
  41241. var keyboard = this.inputs.attached["keyboard"];
  41242. if (keyboard)
  41243. return keyboard.keysLeft;
  41244. return [];
  41245. },
  41246. set: function (value) {
  41247. var keyboard = this.inputs.attached["keyboard"];
  41248. if (keyboard)
  41249. keyboard.keysLeft = value;
  41250. },
  41251. enumerable: true,
  41252. configurable: true
  41253. });
  41254. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41255. get: function () {
  41256. var keyboard = this.inputs.attached["keyboard"];
  41257. if (keyboard)
  41258. return keyboard.keysRight;
  41259. return [];
  41260. },
  41261. set: function (value) {
  41262. var keyboard = this.inputs.attached["keyboard"];
  41263. if (keyboard)
  41264. keyboard.keysRight = value;
  41265. },
  41266. enumerable: true,
  41267. configurable: true
  41268. });
  41269. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41270. get: function () {
  41271. var mousewheel = this.inputs.attached["mousewheel"];
  41272. if (mousewheel)
  41273. return mousewheel.wheelPrecision;
  41274. return 0;
  41275. },
  41276. set: function (value) {
  41277. var mousewheel = this.inputs.attached["mousewheel"];
  41278. if (mousewheel)
  41279. mousewheel.wheelPrecision = value;
  41280. },
  41281. enumerable: true,
  41282. configurable: true
  41283. });
  41284. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41285. get: function () {
  41286. var mousewheel = this.inputs.attached["mousewheel"];
  41287. if (mousewheel)
  41288. return mousewheel.wheelDeltaPercentage;
  41289. return 0;
  41290. },
  41291. set: function (value) {
  41292. var mousewheel = this.inputs.attached["mousewheel"];
  41293. if (mousewheel)
  41294. mousewheel.wheelDeltaPercentage = value;
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41300. get: function () {
  41301. return this._bouncingBehavior;
  41302. },
  41303. enumerable: true,
  41304. configurable: true
  41305. });
  41306. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41307. get: function () {
  41308. return this._bouncingBehavior != null;
  41309. },
  41310. set: function (value) {
  41311. if (value === this.useBouncingBehavior) {
  41312. return;
  41313. }
  41314. if (value) {
  41315. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41316. this.addBehavior(this._bouncingBehavior);
  41317. }
  41318. else if (this._bouncingBehavior) {
  41319. this.removeBehavior(this._bouncingBehavior);
  41320. this._bouncingBehavior = null;
  41321. }
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41327. get: function () {
  41328. return this._framingBehavior;
  41329. },
  41330. enumerable: true,
  41331. configurable: true
  41332. });
  41333. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41334. get: function () {
  41335. return this._framingBehavior != null;
  41336. },
  41337. set: function (value) {
  41338. if (value === this.useFramingBehavior) {
  41339. return;
  41340. }
  41341. if (value) {
  41342. this._framingBehavior = new BABYLON.FramingBehavior();
  41343. this.addBehavior(this._framingBehavior);
  41344. }
  41345. else if (this._framingBehavior) {
  41346. this.removeBehavior(this._framingBehavior);
  41347. this._framingBehavior = null;
  41348. }
  41349. },
  41350. enumerable: true,
  41351. configurable: true
  41352. });
  41353. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41354. get: function () {
  41355. return this._autoRotationBehavior;
  41356. },
  41357. enumerable: true,
  41358. configurable: true
  41359. });
  41360. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41361. get: function () {
  41362. return this._autoRotationBehavior != null;
  41363. },
  41364. set: function (value) {
  41365. if (value === this.useAutoRotationBehavior) {
  41366. return;
  41367. }
  41368. if (value) {
  41369. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41370. this.addBehavior(this._autoRotationBehavior);
  41371. }
  41372. else if (this._autoRotationBehavior) {
  41373. this.removeBehavior(this._autoRotationBehavior);
  41374. this._autoRotationBehavior = null;
  41375. }
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. // Cache
  41381. ArcRotateCamera.prototype._initCache = function () {
  41382. _super.prototype._initCache.call(this);
  41383. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41384. this._cache.alpha = undefined;
  41385. this._cache.beta = undefined;
  41386. this._cache.radius = undefined;
  41387. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41388. };
  41389. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41390. if (!ignoreParentClass) {
  41391. _super.prototype._updateCache.call(this);
  41392. }
  41393. this._cache._target.copyFrom(this._getTargetPosition());
  41394. this._cache.alpha = this.alpha;
  41395. this._cache.beta = this.beta;
  41396. this._cache.radius = this.radius;
  41397. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41398. };
  41399. ArcRotateCamera.prototype._getTargetPosition = function () {
  41400. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41401. var pos = this._targetHost.getAbsolutePosition();
  41402. if (this._targetBoundingCenter) {
  41403. pos.addToRef(this._targetBoundingCenter, this._target);
  41404. }
  41405. else {
  41406. this._target.copyFrom(pos);
  41407. }
  41408. }
  41409. var lockedTargetPosition = this._getLockedTargetPosition();
  41410. if (lockedTargetPosition) {
  41411. return lockedTargetPosition;
  41412. }
  41413. return this._target;
  41414. };
  41415. ArcRotateCamera.prototype.storeState = function () {
  41416. this._storedAlpha = this.alpha;
  41417. this._storedBeta = this.beta;
  41418. this._storedRadius = this.radius;
  41419. this._storedTarget = this._getTargetPosition().clone();
  41420. return _super.prototype.storeState.call(this);
  41421. };
  41422. /**
  41423. * Restored camera state. You must call storeState() first
  41424. */
  41425. ArcRotateCamera.prototype._restoreStateValues = function () {
  41426. if (!_super.prototype._restoreStateValues.call(this)) {
  41427. return false;
  41428. }
  41429. this.alpha = this._storedAlpha;
  41430. this.beta = this._storedBeta;
  41431. this.radius = this._storedRadius;
  41432. this.setTarget(this._storedTarget.clone());
  41433. this.inertialAlphaOffset = 0;
  41434. this.inertialBetaOffset = 0;
  41435. this.inertialRadiusOffset = 0;
  41436. this.inertialPanningX = 0;
  41437. this.inertialPanningY = 0;
  41438. return true;
  41439. };
  41440. // Synchronized
  41441. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41442. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41443. return false;
  41444. return this._cache._target.equals(this._getTargetPosition())
  41445. && this._cache.alpha === this.alpha
  41446. && this._cache.beta === this.beta
  41447. && this._cache.radius === this.radius
  41448. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41449. };
  41450. // Methods
  41451. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41452. var _this = this;
  41453. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41454. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41455. this._useCtrlForPanning = useCtrlForPanning;
  41456. this._panningMouseButton = panningMouseButton;
  41457. this.inputs.attachElement(element, noPreventDefault);
  41458. this._reset = function () {
  41459. _this.inertialAlphaOffset = 0;
  41460. _this.inertialBetaOffset = 0;
  41461. _this.inertialRadiusOffset = 0;
  41462. _this.inertialPanningX = 0;
  41463. _this.inertialPanningY = 0;
  41464. };
  41465. };
  41466. ArcRotateCamera.prototype.detachControl = function (element) {
  41467. this.inputs.detachElement(element);
  41468. if (this._reset) {
  41469. this._reset();
  41470. }
  41471. };
  41472. ArcRotateCamera.prototype._checkInputs = function () {
  41473. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41474. if (this._collisionTriggered) {
  41475. return;
  41476. }
  41477. this.inputs.checkInputs();
  41478. // Inertia
  41479. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41480. if (this.getScene().useRightHandedSystem) {
  41481. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41482. }
  41483. else {
  41484. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41485. }
  41486. this.beta += this.inertialBetaOffset;
  41487. this.radius -= this.inertialRadiusOffset;
  41488. this.inertialAlphaOffset *= this.inertia;
  41489. this.inertialBetaOffset *= this.inertia;
  41490. this.inertialRadiusOffset *= this.inertia;
  41491. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41492. this.inertialAlphaOffset = 0;
  41493. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41494. this.inertialBetaOffset = 0;
  41495. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41496. this.inertialRadiusOffset = 0;
  41497. }
  41498. // Panning inertia
  41499. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41500. if (!this._localDirection) {
  41501. this._localDirection = BABYLON.Vector3.Zero();
  41502. this._transformedDirection = BABYLON.Vector3.Zero();
  41503. }
  41504. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  41505. this._localDirection.multiplyInPlace(this.panningAxis);
  41506. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  41507. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  41508. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  41509. if (!this.panningAxis.y) {
  41510. this._transformedDirection.y = 0;
  41511. }
  41512. if (!this._targetHost) {
  41513. if (this.panningDistanceLimit) {
  41514. this._transformedDirection.addInPlace(this._target);
  41515. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  41516. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  41517. this._target.copyFrom(this._transformedDirection);
  41518. }
  41519. }
  41520. else {
  41521. this._target.addInPlace(this._transformedDirection);
  41522. }
  41523. }
  41524. this.inertialPanningX *= this.panningInertia;
  41525. this.inertialPanningY *= this.panningInertia;
  41526. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  41527. this.inertialPanningX = 0;
  41528. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  41529. this.inertialPanningY = 0;
  41530. }
  41531. // Limits
  41532. this._checkLimits();
  41533. _super.prototype._checkInputs.call(this);
  41534. };
  41535. ArcRotateCamera.prototype._checkLimits = function () {
  41536. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  41537. if (this.allowUpsideDown && this.beta > Math.PI) {
  41538. this.beta = this.beta - (2 * Math.PI);
  41539. }
  41540. }
  41541. else {
  41542. if (this.beta < this.lowerBetaLimit) {
  41543. this.beta = this.lowerBetaLimit;
  41544. }
  41545. }
  41546. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  41547. if (this.allowUpsideDown && this.beta < -Math.PI) {
  41548. this.beta = this.beta + (2 * Math.PI);
  41549. }
  41550. }
  41551. else {
  41552. if (this.beta > this.upperBetaLimit) {
  41553. this.beta = this.upperBetaLimit;
  41554. }
  41555. }
  41556. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  41557. this.alpha = this.lowerAlphaLimit;
  41558. }
  41559. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  41560. this.alpha = this.upperAlphaLimit;
  41561. }
  41562. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  41563. this.radius = this.lowerRadiusLimit;
  41564. }
  41565. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  41566. this.radius = this.upperRadiusLimit;
  41567. }
  41568. };
  41569. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  41570. var radiusv3 = this.position.subtract(this._getTargetPosition());
  41571. this.radius = radiusv3.length();
  41572. if (this.radius === 0) {
  41573. this.radius = 0.0001; // Just to avoid division by zero
  41574. }
  41575. // Alpha
  41576. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  41577. if (radiusv3.z < 0) {
  41578. this.alpha = 2 * Math.PI - this.alpha;
  41579. }
  41580. // Beta
  41581. this.beta = Math.acos(radiusv3.y / this.radius);
  41582. this._checkLimits();
  41583. };
  41584. ArcRotateCamera.prototype.setPosition = function (position) {
  41585. if (this.position.equals(position)) {
  41586. return;
  41587. }
  41588. this.position.copyFrom(position);
  41589. this.rebuildAnglesAndRadius();
  41590. };
  41591. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  41592. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  41593. if (allowSamePosition === void 0) { allowSamePosition = false; }
  41594. if (target.getBoundingInfo) {
  41595. if (toBoundingCenter) {
  41596. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  41597. }
  41598. else {
  41599. this._targetBoundingCenter = null;
  41600. }
  41601. this._targetHost = target;
  41602. this._target = this._getTargetPosition();
  41603. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  41604. }
  41605. else {
  41606. var newTarget = target;
  41607. var currentTarget = this._getTargetPosition();
  41608. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  41609. return;
  41610. }
  41611. this._targetHost = null;
  41612. this._target = newTarget;
  41613. this._targetBoundingCenter = null;
  41614. this.onMeshTargetChangedObservable.notifyObservers(null);
  41615. }
  41616. this.rebuildAnglesAndRadius();
  41617. };
  41618. ArcRotateCamera.prototype._getViewMatrix = function () {
  41619. // Compute
  41620. var cosa = Math.cos(this.alpha);
  41621. var sina = Math.sin(this.alpha);
  41622. var cosb = Math.cos(this.beta);
  41623. var sinb = Math.sin(this.beta);
  41624. if (sinb === 0) {
  41625. sinb = 0.0001;
  41626. }
  41627. var target = this._getTargetPosition();
  41628. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  41629. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  41630. if (!this._collider) {
  41631. this._collider = new BABYLON.Collider();
  41632. }
  41633. this._collider._radius = this.collisionRadius;
  41634. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  41635. this._collisionTriggered = true;
  41636. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41637. }
  41638. else {
  41639. this.position.copyFrom(this._newPosition);
  41640. var up = this.upVector;
  41641. if (this.allowUpsideDown && sinb < 0) {
  41642. up = up.clone();
  41643. up = up.negate();
  41644. }
  41645. if (this.getScene().useRightHandedSystem) {
  41646. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  41647. }
  41648. else {
  41649. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  41650. }
  41651. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  41652. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  41653. }
  41654. this._currentTarget = target;
  41655. return this._viewMatrix;
  41656. };
  41657. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  41658. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41659. meshes = meshes || this.getScene().meshes;
  41660. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  41661. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  41662. this.radius = distance * this.zoomOnFactor;
  41663. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  41664. };
  41665. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  41666. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41667. var meshesOrMinMaxVector;
  41668. var distance;
  41669. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  41670. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  41671. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  41672. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  41673. }
  41674. else {
  41675. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  41676. meshesOrMinMaxVector = minMaxVectorAndDistance;
  41677. distance = minMaxVectorAndDistance.distance;
  41678. }
  41679. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  41680. if (!doNotUpdateMaxZ) {
  41681. this.maxZ = distance * 2;
  41682. }
  41683. };
  41684. /**
  41685. * @override
  41686. * Override Camera.createRigCamera
  41687. */
  41688. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41689. var alphaShift = 0;
  41690. switch (this.cameraRigMode) {
  41691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41694. case BABYLON.Camera.RIG_MODE_VR:
  41695. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  41696. break;
  41697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41698. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  41699. break;
  41700. }
  41701. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  41702. rigCam._cameraRigParams = {};
  41703. return rigCam;
  41704. };
  41705. /**
  41706. * @override
  41707. * Override Camera._updateRigCameras
  41708. */
  41709. ArcRotateCamera.prototype._updateRigCameras = function () {
  41710. var camLeft = this._rigCameras[0];
  41711. var camRight = this._rigCameras[1];
  41712. camLeft.beta = camRight.beta = this.beta;
  41713. camLeft.radius = camRight.radius = this.radius;
  41714. switch (this.cameraRigMode) {
  41715. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41718. case BABYLON.Camera.RIG_MODE_VR:
  41719. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41720. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41721. break;
  41722. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41723. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41724. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41725. break;
  41726. }
  41727. _super.prototype._updateRigCameras.call(this);
  41728. };
  41729. ArcRotateCamera.prototype.dispose = function () {
  41730. this.inputs.clear();
  41731. _super.prototype.dispose.call(this);
  41732. };
  41733. ArcRotateCamera.prototype.getClassName = function () {
  41734. return "ArcRotateCamera";
  41735. };
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ArcRotateCamera.prototype, "alpha", void 0);
  41739. __decorate([
  41740. BABYLON.serialize()
  41741. ], ArcRotateCamera.prototype, "beta", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ArcRotateCamera.prototype, "radius", void 0);
  41745. __decorate([
  41746. BABYLON.serializeAsVector3("target")
  41747. ], ArcRotateCamera.prototype, "_target", void 0);
  41748. __decorate([
  41749. BABYLON.serialize()
  41750. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41754. __decorate([
  41755. BABYLON.serialize()
  41756. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41757. __decorate([
  41758. BABYLON.serialize()
  41759. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41766. __decorate([
  41767. BABYLON.serialize()
  41768. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41769. __decorate([
  41770. BABYLON.serialize()
  41771. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41772. __decorate([
  41773. BABYLON.serialize()
  41774. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41775. __decorate([
  41776. BABYLON.serialize()
  41777. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41778. __decorate([
  41779. BABYLON.serialize()
  41780. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41781. __decorate([
  41782. BABYLON.serialize()
  41783. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41784. __decorate([
  41785. BABYLON.serialize()
  41786. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41787. __decorate([
  41788. BABYLON.serializeAsVector3()
  41789. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41790. __decorate([
  41791. BABYLON.serialize()
  41792. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41793. __decorate([
  41794. BABYLON.serialize()
  41795. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41796. __decorate([
  41797. BABYLON.serialize()
  41798. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41799. return ArcRotateCamera;
  41800. }(BABYLON.TargetCamera));
  41801. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41802. })(BABYLON || (BABYLON = {}));
  41803. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41804. var BABYLON;
  41805. (function (BABYLON) {
  41806. var HemisphericLight = /** @class */ (function (_super) {
  41807. __extends(HemisphericLight, _super);
  41808. /**
  41809. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41810. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41811. * The HemisphericLight can't cast shadows.
  41812. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41813. */
  41814. function HemisphericLight(name, direction, scene) {
  41815. var _this = _super.call(this, name, scene) || this;
  41816. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41817. _this.direction = direction || BABYLON.Vector3.Up();
  41818. return _this;
  41819. }
  41820. HemisphericLight.prototype._buildUniformLayout = function () {
  41821. this._uniformBuffer.addUniform("vLightData", 4);
  41822. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41823. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41824. this._uniformBuffer.addUniform("vLightGround", 3);
  41825. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41826. this._uniformBuffer.addUniform("depthValues", 2);
  41827. this._uniformBuffer.create();
  41828. };
  41829. /**
  41830. * Returns the string "HemisphericLight".
  41831. */
  41832. HemisphericLight.prototype.getClassName = function () {
  41833. return "HemisphericLight";
  41834. };
  41835. /**
  41836. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41837. * Returns the updated direction.
  41838. */
  41839. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41840. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41841. return this.direction;
  41842. };
  41843. HemisphericLight.prototype.getShadowGenerator = function () {
  41844. return null;
  41845. };
  41846. /**
  41847. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41848. * Returns the HemisphericLight.
  41849. */
  41850. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41851. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41852. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41853. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41854. return this;
  41855. };
  41856. HemisphericLight.prototype._getWorldMatrix = function () {
  41857. if (!this._worldMatrix) {
  41858. this._worldMatrix = BABYLON.Matrix.Identity();
  41859. }
  41860. return this._worldMatrix;
  41861. };
  41862. /**
  41863. * Returns the integer 3.
  41864. */
  41865. HemisphericLight.prototype.getTypeID = function () {
  41866. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41867. };
  41868. __decorate([
  41869. BABYLON.serializeAsColor3()
  41870. ], HemisphericLight.prototype, "groundColor", void 0);
  41871. __decorate([
  41872. BABYLON.serializeAsVector3()
  41873. ], HemisphericLight.prototype, "direction", void 0);
  41874. return HemisphericLight;
  41875. }(BABYLON.Light));
  41876. BABYLON.HemisphericLight = HemisphericLight;
  41877. })(BABYLON || (BABYLON = {}));
  41878. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41879. var BABYLON;
  41880. (function (BABYLON) {
  41881. var ShadowLight = /** @class */ (function (_super) {
  41882. __extends(ShadowLight, _super);
  41883. function ShadowLight() {
  41884. var _this = _super !== null && _super.apply(this, arguments) || this;
  41885. _this._needProjectionMatrixCompute = true;
  41886. return _this;
  41887. }
  41888. Object.defineProperty(ShadowLight.prototype, "direction", {
  41889. get: function () {
  41890. return this._direction;
  41891. },
  41892. set: function (value) {
  41893. this._direction = value;
  41894. },
  41895. enumerable: true,
  41896. configurable: true
  41897. });
  41898. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41899. get: function () {
  41900. return this._shadowMinZ;
  41901. },
  41902. set: function (value) {
  41903. this._shadowMinZ = value;
  41904. this.forceProjectionMatrixCompute();
  41905. },
  41906. enumerable: true,
  41907. configurable: true
  41908. });
  41909. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41910. get: function () {
  41911. return this._shadowMaxZ;
  41912. },
  41913. set: function (value) {
  41914. this._shadowMaxZ = value;
  41915. this.forceProjectionMatrixCompute();
  41916. },
  41917. enumerable: true,
  41918. configurable: true
  41919. });
  41920. /**
  41921. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41922. */
  41923. ShadowLight.prototype.computeTransformedInformation = function () {
  41924. if (this.parent && this.parent.getWorldMatrix) {
  41925. if (!this.transformedPosition) {
  41926. this.transformedPosition = BABYLON.Vector3.Zero();
  41927. }
  41928. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41929. // In case the direction is present.
  41930. if (this.direction) {
  41931. if (!this.transformedDirection) {
  41932. this.transformedDirection = BABYLON.Vector3.Zero();
  41933. }
  41934. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41935. }
  41936. return true;
  41937. }
  41938. return false;
  41939. };
  41940. /**
  41941. * Return the depth scale used for the shadow map.
  41942. */
  41943. ShadowLight.prototype.getDepthScale = function () {
  41944. return 50.0;
  41945. };
  41946. /**
  41947. * Returns the light direction (Vector3) for any passed face index.
  41948. */
  41949. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41950. return this.transformedDirection ? this.transformedDirection : this.direction;
  41951. };
  41952. /**
  41953. * Returns the ShadowLight absolute position in the World.
  41954. */
  41955. ShadowLight.prototype.getAbsolutePosition = function () {
  41956. return this.transformedPosition ? this.transformedPosition : this.position;
  41957. };
  41958. /**
  41959. * Sets the ShadowLight direction toward the passed target (Vector3).
  41960. * Returns the updated ShadowLight direction (Vector3).
  41961. */
  41962. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41963. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41964. return this.direction;
  41965. };
  41966. /**
  41967. * Returns the light rotation (Vector3).
  41968. */
  41969. ShadowLight.prototype.getRotation = function () {
  41970. this.direction.normalize();
  41971. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41972. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41973. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41974. };
  41975. /**
  41976. * Boolean : false by default.
  41977. */
  41978. ShadowLight.prototype.needCube = function () {
  41979. return false;
  41980. };
  41981. /**
  41982. * Specifies wether or not the projection matrix should be recomputed this frame.
  41983. */
  41984. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41985. return this._needProjectionMatrixCompute;
  41986. };
  41987. /**
  41988. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41989. */
  41990. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41991. this._needProjectionMatrixCompute = true;
  41992. };
  41993. /**
  41994. * Get the world matrix of the sahdow lights.
  41995. */
  41996. ShadowLight.prototype._getWorldMatrix = function () {
  41997. if (!this._worldMatrix) {
  41998. this._worldMatrix = BABYLON.Matrix.Identity();
  41999. }
  42000. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42001. return this._worldMatrix;
  42002. };
  42003. /**
  42004. * Gets the minZ used for shadow according to both the scene and the light.
  42005. * @param activeCamera
  42006. */
  42007. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42008. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42009. };
  42010. /**
  42011. * Gets the maxZ used for shadow according to both the scene and the light.
  42012. * @param activeCamera
  42013. */
  42014. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42015. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42016. };
  42017. /**
  42018. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42019. * Returns the light.
  42020. */
  42021. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42022. if (this.customProjectionMatrixBuilder) {
  42023. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42024. }
  42025. else {
  42026. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42027. }
  42028. return this;
  42029. };
  42030. __decorate([
  42031. BABYLON.serializeAsVector3()
  42032. ], ShadowLight.prototype, "position", void 0);
  42033. __decorate([
  42034. BABYLON.serializeAsVector3()
  42035. ], ShadowLight.prototype, "direction", null);
  42036. __decorate([
  42037. BABYLON.serialize()
  42038. ], ShadowLight.prototype, "shadowMinZ", null);
  42039. __decorate([
  42040. BABYLON.serialize()
  42041. ], ShadowLight.prototype, "shadowMaxZ", null);
  42042. return ShadowLight;
  42043. }(BABYLON.Light));
  42044. BABYLON.ShadowLight = ShadowLight;
  42045. })(BABYLON || (BABYLON = {}));
  42046. //# sourceMappingURL=babylon.shadowLight.js.map
  42047. var BABYLON;
  42048. (function (BABYLON) {
  42049. var PointLight = /** @class */ (function (_super) {
  42050. __extends(PointLight, _super);
  42051. /**
  42052. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42053. * A PointLight emits the light in every direction.
  42054. * It can cast shadows.
  42055. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42056. * ```javascript
  42057. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42058. * ```
  42059. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42060. */
  42061. function PointLight(name, position, scene) {
  42062. var _this = _super.call(this, name, scene) || this;
  42063. _this._shadowAngle = Math.PI / 2;
  42064. _this.position = position;
  42065. return _this;
  42066. }
  42067. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42068. /**
  42069. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42070. * This specifies what angle the shadow will use to be created.
  42071. *
  42072. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42073. */
  42074. get: function () {
  42075. return this._shadowAngle;
  42076. },
  42077. /**
  42078. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42079. * This specifies what angle the shadow will use to be created.
  42080. *
  42081. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42082. */
  42083. set: function (value) {
  42084. this._shadowAngle = value;
  42085. this.forceProjectionMatrixCompute();
  42086. },
  42087. enumerable: true,
  42088. configurable: true
  42089. });
  42090. Object.defineProperty(PointLight.prototype, "direction", {
  42091. get: function () {
  42092. return this._direction;
  42093. },
  42094. /**
  42095. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42096. */
  42097. set: function (value) {
  42098. var previousNeedCube = this.needCube();
  42099. this._direction = value;
  42100. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42101. this._shadowGenerator.recreateShadowMap();
  42102. }
  42103. },
  42104. enumerable: true,
  42105. configurable: true
  42106. });
  42107. /**
  42108. * Returns the string "PointLight"
  42109. */
  42110. PointLight.prototype.getClassName = function () {
  42111. return "PointLight";
  42112. };
  42113. /**
  42114. * Returns the integer 0.
  42115. */
  42116. PointLight.prototype.getTypeID = function () {
  42117. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42118. };
  42119. /**
  42120. * Specifies wether or not the shadowmap should be a cube texture.
  42121. */
  42122. PointLight.prototype.needCube = function () {
  42123. return !this.direction;
  42124. };
  42125. /**
  42126. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42127. */
  42128. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42129. if (this.direction) {
  42130. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42131. }
  42132. else {
  42133. switch (faceIndex) {
  42134. case 0:
  42135. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42136. case 1:
  42137. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42138. case 2:
  42139. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42140. case 3:
  42141. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42142. case 4:
  42143. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42144. case 5:
  42145. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42146. }
  42147. }
  42148. return BABYLON.Vector3.Zero();
  42149. };
  42150. /**
  42151. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42152. * - fov = PI / 2
  42153. * - aspect ratio : 1.0
  42154. * - z-near and far equal to the active camera minZ and maxZ.
  42155. * Returns the PointLight.
  42156. */
  42157. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42158. var activeCamera = this.getScene().activeCamera;
  42159. if (!activeCamera) {
  42160. return;
  42161. }
  42162. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42163. };
  42164. PointLight.prototype._buildUniformLayout = function () {
  42165. this._uniformBuffer.addUniform("vLightData", 4);
  42166. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42167. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42168. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42169. this._uniformBuffer.addUniform("depthValues", 2);
  42170. this._uniformBuffer.create();
  42171. };
  42172. /**
  42173. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42174. * Returns the PointLight.
  42175. */
  42176. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42177. if (this.computeTransformedInformation()) {
  42178. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42179. return this;
  42180. }
  42181. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42182. return this;
  42183. };
  42184. __decorate([
  42185. BABYLON.serialize()
  42186. ], PointLight.prototype, "shadowAngle", null);
  42187. return PointLight;
  42188. }(BABYLON.ShadowLight));
  42189. BABYLON.PointLight = PointLight;
  42190. })(BABYLON || (BABYLON = {}));
  42191. //# sourceMappingURL=babylon.pointLight.js.map
  42192. var BABYLON;
  42193. (function (BABYLON) {
  42194. var DirectionalLight = /** @class */ (function (_super) {
  42195. __extends(DirectionalLight, _super);
  42196. /**
  42197. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42198. * The directional light is emitted from everywhere in the given direction.
  42199. * It can cast shawdows.
  42200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42201. */
  42202. function DirectionalLight(name, direction, scene) {
  42203. var _this = _super.call(this, name, scene) || this;
  42204. _this._shadowFrustumSize = 0;
  42205. _this._shadowOrthoScale = 0.5;
  42206. _this.autoUpdateExtends = true;
  42207. // Cache
  42208. _this._orthoLeft = Number.MAX_VALUE;
  42209. _this._orthoRight = Number.MIN_VALUE;
  42210. _this._orthoTop = Number.MIN_VALUE;
  42211. _this._orthoBottom = Number.MAX_VALUE;
  42212. _this.position = direction.scale(-1.0);
  42213. _this.direction = direction;
  42214. return _this;
  42215. }
  42216. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42217. /**
  42218. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42219. */
  42220. get: function () {
  42221. return this._shadowFrustumSize;
  42222. },
  42223. /**
  42224. * Specifies a fix frustum size for the shadow generation.
  42225. */
  42226. set: function (value) {
  42227. this._shadowFrustumSize = value;
  42228. this.forceProjectionMatrixCompute();
  42229. },
  42230. enumerable: true,
  42231. configurable: true
  42232. });
  42233. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42234. get: function () {
  42235. return this._shadowOrthoScale;
  42236. },
  42237. set: function (value) {
  42238. this._shadowOrthoScale = value;
  42239. this.forceProjectionMatrixCompute();
  42240. },
  42241. enumerable: true,
  42242. configurable: true
  42243. });
  42244. /**
  42245. * Returns the string "DirectionalLight".
  42246. */
  42247. DirectionalLight.prototype.getClassName = function () {
  42248. return "DirectionalLight";
  42249. };
  42250. /**
  42251. * Returns the integer 1.
  42252. */
  42253. DirectionalLight.prototype.getTypeID = function () {
  42254. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42255. };
  42256. /**
  42257. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42258. * Returns the DirectionalLight Shadow projection matrix.
  42259. */
  42260. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42261. if (this.shadowFrustumSize > 0) {
  42262. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42263. }
  42264. else {
  42265. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42266. }
  42267. };
  42268. /**
  42269. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42270. * Returns the DirectionalLight Shadow projection matrix.
  42271. */
  42272. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42273. var activeCamera = this.getScene().activeCamera;
  42274. if (!activeCamera) {
  42275. return;
  42276. }
  42277. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42278. };
  42279. /**
  42280. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42281. * Returns the DirectionalLight Shadow projection matrix.
  42282. */
  42283. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42284. var activeCamera = this.getScene().activeCamera;
  42285. if (!activeCamera) {
  42286. return;
  42287. }
  42288. // Check extends
  42289. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42290. var tempVector3 = BABYLON.Vector3.Zero();
  42291. this._orthoLeft = Number.MAX_VALUE;
  42292. this._orthoRight = Number.MIN_VALUE;
  42293. this._orthoTop = Number.MIN_VALUE;
  42294. this._orthoBottom = Number.MAX_VALUE;
  42295. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42296. var mesh = renderList[meshIndex];
  42297. if (!mesh) {
  42298. continue;
  42299. }
  42300. var boundingInfo = mesh.getBoundingInfo();
  42301. var boundingBox = boundingInfo.boundingBox;
  42302. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42303. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42304. if (tempVector3.x < this._orthoLeft)
  42305. this._orthoLeft = tempVector3.x;
  42306. if (tempVector3.y < this._orthoBottom)
  42307. this._orthoBottom = tempVector3.y;
  42308. if (tempVector3.x > this._orthoRight)
  42309. this._orthoRight = tempVector3.x;
  42310. if (tempVector3.y > this._orthoTop)
  42311. this._orthoTop = tempVector3.y;
  42312. }
  42313. }
  42314. }
  42315. var xOffset = this._orthoRight - this._orthoLeft;
  42316. var yOffset = this._orthoTop - this._orthoBottom;
  42317. 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);
  42318. };
  42319. DirectionalLight.prototype._buildUniformLayout = function () {
  42320. this._uniformBuffer.addUniform("vLightData", 4);
  42321. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42322. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42323. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42324. this._uniformBuffer.addUniform("depthValues", 2);
  42325. this._uniformBuffer.create();
  42326. };
  42327. /**
  42328. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42329. * Returns the DirectionalLight.
  42330. */
  42331. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42332. if (this.computeTransformedInformation()) {
  42333. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42334. return this;
  42335. }
  42336. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42337. return this;
  42338. };
  42339. /**
  42340. * Gets the minZ used for shadow according to both the scene and the light.
  42341. *
  42342. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42343. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42344. * @param activeCamera
  42345. */
  42346. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42347. return 1;
  42348. };
  42349. /**
  42350. * Gets the maxZ used for shadow according to both the scene and the light.
  42351. *
  42352. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42353. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42354. * @param activeCamera
  42355. */
  42356. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42357. return 1;
  42358. };
  42359. __decorate([
  42360. BABYLON.serialize()
  42361. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42362. __decorate([
  42363. BABYLON.serialize()
  42364. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42365. __decorate([
  42366. BABYLON.serialize()
  42367. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42368. return DirectionalLight;
  42369. }(BABYLON.ShadowLight));
  42370. BABYLON.DirectionalLight = DirectionalLight;
  42371. })(BABYLON || (BABYLON = {}));
  42372. //# sourceMappingURL=babylon.directionalLight.js.map
  42373. var BABYLON;
  42374. (function (BABYLON) {
  42375. var SpotLight = /** @class */ (function (_super) {
  42376. __extends(SpotLight, _super);
  42377. /**
  42378. * Creates a SpotLight object in the scene with the passed parameters :
  42379. * - `position` (Vector3) is the initial SpotLight position,
  42380. * - `direction` (Vector3) is the initial SpotLight direction,
  42381. * - `angle` (float, in radians) is the spot light cone angle,
  42382. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42383. * A spot light is a simply light oriented cone.
  42384. * It can cast shadows.
  42385. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42386. */
  42387. function SpotLight(name, position, direction, angle, exponent, scene) {
  42388. var _this = _super.call(this, name, scene) || this;
  42389. _this.position = position;
  42390. _this.direction = direction;
  42391. _this.angle = angle;
  42392. _this.exponent = exponent;
  42393. return _this;
  42394. }
  42395. Object.defineProperty(SpotLight.prototype, "angle", {
  42396. get: function () {
  42397. return this._angle;
  42398. },
  42399. set: function (value) {
  42400. this._angle = value;
  42401. this.forceProjectionMatrixCompute();
  42402. },
  42403. enumerable: true,
  42404. configurable: true
  42405. });
  42406. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42407. get: function () {
  42408. return this._shadowAngleScale;
  42409. },
  42410. /**
  42411. * Allows scaling the angle of the light for shadow generation only.
  42412. */
  42413. set: function (value) {
  42414. this._shadowAngleScale = value;
  42415. this.forceProjectionMatrixCompute();
  42416. },
  42417. enumerable: true,
  42418. configurable: true
  42419. });
  42420. /**
  42421. * Returns the string "SpotLight".
  42422. */
  42423. SpotLight.prototype.getClassName = function () {
  42424. return "SpotLight";
  42425. };
  42426. /**
  42427. * Returns the integer 2.
  42428. */
  42429. SpotLight.prototype.getTypeID = function () {
  42430. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42431. };
  42432. /**
  42433. * 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.
  42434. * Returns the SpotLight.
  42435. */
  42436. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42437. var activeCamera = this.getScene().activeCamera;
  42438. if (!activeCamera) {
  42439. return;
  42440. }
  42441. this._shadowAngleScale = this._shadowAngleScale || 1;
  42442. var angle = this._shadowAngleScale * this._angle;
  42443. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42444. };
  42445. SpotLight.prototype._buildUniformLayout = function () {
  42446. this._uniformBuffer.addUniform("vLightData", 4);
  42447. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42448. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42449. this._uniformBuffer.addUniform("vLightDirection", 3);
  42450. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42451. this._uniformBuffer.addUniform("depthValues", 2);
  42452. this._uniformBuffer.create();
  42453. };
  42454. /**
  42455. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42456. * Return the SpotLight.
  42457. */
  42458. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42459. var normalizeDirection;
  42460. if (this.computeTransformedInformation()) {
  42461. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42462. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42463. }
  42464. else {
  42465. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42466. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42467. }
  42468. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42469. return this;
  42470. };
  42471. __decorate([
  42472. BABYLON.serialize()
  42473. ], SpotLight.prototype, "angle", null);
  42474. __decorate([
  42475. BABYLON.serialize()
  42476. /**
  42477. * Allows scaling the angle of the light for shadow generation only.
  42478. */
  42479. ], SpotLight.prototype, "shadowAngleScale", null);
  42480. __decorate([
  42481. BABYLON.serialize()
  42482. ], SpotLight.prototype, "exponent", void 0);
  42483. return SpotLight;
  42484. }(BABYLON.ShadowLight));
  42485. BABYLON.SpotLight = SpotLight;
  42486. })(BABYLON || (BABYLON = {}));
  42487. //# sourceMappingURL=babylon.spotLight.js.map
  42488. var BABYLON;
  42489. (function (BABYLON) {
  42490. var AnimationRange = /** @class */ (function () {
  42491. function AnimationRange(name, from, to) {
  42492. this.name = name;
  42493. this.from = from;
  42494. this.to = to;
  42495. }
  42496. AnimationRange.prototype.clone = function () {
  42497. return new AnimationRange(this.name, this.from, this.to);
  42498. };
  42499. return AnimationRange;
  42500. }());
  42501. BABYLON.AnimationRange = AnimationRange;
  42502. /**
  42503. * Composed of a frame, and an action function
  42504. */
  42505. var AnimationEvent = /** @class */ (function () {
  42506. function AnimationEvent(frame, action, onlyOnce) {
  42507. this.frame = frame;
  42508. this.action = action;
  42509. this.onlyOnce = onlyOnce;
  42510. this.isDone = false;
  42511. }
  42512. return AnimationEvent;
  42513. }());
  42514. BABYLON.AnimationEvent = AnimationEvent;
  42515. var PathCursor = /** @class */ (function () {
  42516. function PathCursor(path) {
  42517. this.path = path;
  42518. this._onchange = new Array();
  42519. this.value = 0;
  42520. this.animations = new Array();
  42521. }
  42522. PathCursor.prototype.getPoint = function () {
  42523. var point = this.path.getPointAtLengthPosition(this.value);
  42524. return new BABYLON.Vector3(point.x, 0, point.y);
  42525. };
  42526. PathCursor.prototype.moveAhead = function (step) {
  42527. if (step === void 0) { step = 0.002; }
  42528. this.move(step);
  42529. return this;
  42530. };
  42531. PathCursor.prototype.moveBack = function (step) {
  42532. if (step === void 0) { step = 0.002; }
  42533. this.move(-step);
  42534. return this;
  42535. };
  42536. PathCursor.prototype.move = function (step) {
  42537. if (Math.abs(step) > 1) {
  42538. throw "step size should be less than 1.";
  42539. }
  42540. this.value += step;
  42541. this.ensureLimits();
  42542. this.raiseOnChange();
  42543. return this;
  42544. };
  42545. PathCursor.prototype.ensureLimits = function () {
  42546. while (this.value > 1) {
  42547. this.value -= 1;
  42548. }
  42549. while (this.value < 0) {
  42550. this.value += 1;
  42551. }
  42552. return this;
  42553. };
  42554. // used by animation engine
  42555. PathCursor.prototype.raiseOnChange = function () {
  42556. var _this = this;
  42557. this._onchange.forEach(function (f) { return f(_this); });
  42558. return this;
  42559. };
  42560. PathCursor.prototype.onchange = function (f) {
  42561. this._onchange.push(f);
  42562. return this;
  42563. };
  42564. return PathCursor;
  42565. }());
  42566. BABYLON.PathCursor = PathCursor;
  42567. var AnimationKeyInterpolation;
  42568. (function (AnimationKeyInterpolation) {
  42569. /**
  42570. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  42571. */
  42572. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  42573. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  42574. var Animation = /** @class */ (function () {
  42575. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  42576. this.name = name;
  42577. this.targetProperty = targetProperty;
  42578. this.framePerSecond = framePerSecond;
  42579. this.dataType = dataType;
  42580. this.loopMode = loopMode;
  42581. this.enableBlending = enableBlending;
  42582. this._runtimeAnimations = new Array();
  42583. // The set of event that will be linked to this animation
  42584. this._events = new Array();
  42585. this.blendingSpeed = 0.01;
  42586. this._ranges = {};
  42587. this.targetPropertyPath = targetProperty.split(".");
  42588. this.dataType = dataType;
  42589. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  42590. }
  42591. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  42592. var dataType = undefined;
  42593. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  42594. dataType = Animation.ANIMATIONTYPE_FLOAT;
  42595. }
  42596. else if (from instanceof BABYLON.Quaternion) {
  42597. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  42598. }
  42599. else if (from instanceof BABYLON.Vector3) {
  42600. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  42601. }
  42602. else if (from instanceof BABYLON.Vector2) {
  42603. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  42604. }
  42605. else if (from instanceof BABYLON.Color3) {
  42606. dataType = Animation.ANIMATIONTYPE_COLOR3;
  42607. }
  42608. else if (from instanceof BABYLON.Size) {
  42609. dataType = Animation.ANIMATIONTYPE_SIZE;
  42610. }
  42611. if (dataType == undefined) {
  42612. return null;
  42613. }
  42614. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  42615. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  42616. animation.setKeys(keys);
  42617. if (easingFunction !== undefined) {
  42618. animation.setEasingFunction(easingFunction);
  42619. }
  42620. return animation;
  42621. };
  42622. /**
  42623. * Sets up an animation.
  42624. * @param property the property to animate
  42625. * @param animationType the animation type to apply
  42626. * @param easingFunction the easing function used in the animation
  42627. * @returns The created animation
  42628. */
  42629. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  42630. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  42631. animation.setEasingFunction(easingFunction);
  42632. return animation;
  42633. };
  42634. /**
  42635. * Create and start an animation on a node
  42636. * @param {string} name defines the name of the global animation that will be run on all nodes
  42637. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42638. * @param {string} targetProperty defines property to animate
  42639. * @param {number} framePerSecond defines the number of frame per second yo use
  42640. * @param {number} totalFrame defines the number of frames in total
  42641. * @param {any} from defines the initial value
  42642. * @param {any} to defines the final value
  42643. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42644. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42645. * @param onAnimationEnd defines the callback to call when animation end
  42646. * @returns the animatable created for this animation
  42647. */
  42648. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42649. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42650. if (!animation) {
  42651. return null;
  42652. }
  42653. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42654. };
  42655. /**
  42656. * Create and start an animation on a node and its descendants
  42657. * @param {string} name defines the name of the global animation that will be run on all nodes
  42658. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42659. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  42660. * @param {string} targetProperty defines property to animate
  42661. * @param {number} framePerSecond defines the number of frame per second yo use
  42662. * @param {number} totalFrame defines the number of frames in total
  42663. * @param {any} from defines the initial value
  42664. * @param {any} to defines the final value
  42665. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42666. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42667. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  42668. * @returns the list of animatables created for all nodes
  42669. * @example https://www.babylonjs-playground.com/#MH0VLI
  42670. */
  42671. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42672. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42673. if (!animation) {
  42674. return null;
  42675. }
  42676. var scene = node.getScene();
  42677. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42678. };
  42679. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42680. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42681. if (!animation) {
  42682. return null;
  42683. }
  42684. node.animations.push(animation);
  42685. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42686. };
  42687. /**
  42688. * Transition property of the Camera to the target Value.
  42689. * @param property The property to transition
  42690. * @param targetValue The target Value of the property
  42691. * @param host The object where the property to animate belongs
  42692. * @param scene Scene used to run the animation
  42693. * @param frameRate Framerate (in frame/s) to use
  42694. * @param transition The transition type we want to use
  42695. * @param duration The duration of the animation, in milliseconds
  42696. * @param onAnimationEnd Call back trigger at the end of the animation.
  42697. */
  42698. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  42699. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  42700. if (duration <= 0) {
  42701. host[property] = targetValue;
  42702. if (onAnimationEnd) {
  42703. onAnimationEnd();
  42704. }
  42705. return null;
  42706. }
  42707. var endFrame = frameRate * (duration / 1000);
  42708. transition.setKeys([{
  42709. frame: 0,
  42710. value: host[property].clone ? host[property].clone() : host[property]
  42711. },
  42712. {
  42713. frame: endFrame,
  42714. value: targetValue
  42715. }]);
  42716. if (!host.animations) {
  42717. host.animations = [];
  42718. }
  42719. host.animations.push(transition);
  42720. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42721. animation.onAnimationEnd = onAnimationEnd;
  42722. return animation;
  42723. };
  42724. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42725. /**
  42726. * Return the array of runtime animations currently using this animation
  42727. */
  42728. get: function () {
  42729. return this._runtimeAnimations;
  42730. },
  42731. enumerable: true,
  42732. configurable: true
  42733. });
  42734. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42735. get: function () {
  42736. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42737. var runtimeAnimation = _a[_i];
  42738. if (!runtimeAnimation.isStopped) {
  42739. return true;
  42740. }
  42741. }
  42742. return false;
  42743. },
  42744. enumerable: true,
  42745. configurable: true
  42746. });
  42747. // Methods
  42748. /**
  42749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42750. */
  42751. Animation.prototype.toString = function (fullDetails) {
  42752. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42753. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42754. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42755. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42756. if (fullDetails) {
  42757. ret += ", Ranges: {";
  42758. var first = true;
  42759. for (var name in this._ranges) {
  42760. if (first) {
  42761. ret += ", ";
  42762. first = false;
  42763. }
  42764. ret += name;
  42765. }
  42766. ret += "}";
  42767. }
  42768. return ret;
  42769. };
  42770. /**
  42771. * Add an event to this animation.
  42772. */
  42773. Animation.prototype.addEvent = function (event) {
  42774. this._events.push(event);
  42775. };
  42776. /**
  42777. * Remove all events found at the given frame
  42778. * @param frame
  42779. */
  42780. Animation.prototype.removeEvents = function (frame) {
  42781. for (var index = 0; index < this._events.length; index++) {
  42782. if (this._events[index].frame === frame) {
  42783. this._events.splice(index, 1);
  42784. index--;
  42785. }
  42786. }
  42787. };
  42788. Animation.prototype.getEvents = function () {
  42789. return this._events;
  42790. };
  42791. Animation.prototype.createRange = function (name, from, to) {
  42792. // check name not already in use; could happen for bones after serialized
  42793. if (!this._ranges[name]) {
  42794. this._ranges[name] = new AnimationRange(name, from, to);
  42795. }
  42796. };
  42797. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42798. if (deleteFrames === void 0) { deleteFrames = true; }
  42799. var range = this._ranges[name];
  42800. if (!range) {
  42801. return;
  42802. }
  42803. if (deleteFrames) {
  42804. var from = range.from;
  42805. var to = range.to;
  42806. // this loop MUST go high to low for multiple splices to work
  42807. for (var key = this._keys.length - 1; key >= 0; key--) {
  42808. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42809. this._keys.splice(key, 1);
  42810. }
  42811. }
  42812. }
  42813. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42814. };
  42815. Animation.prototype.getRange = function (name) {
  42816. return this._ranges[name];
  42817. };
  42818. Animation.prototype.getKeys = function () {
  42819. return this._keys;
  42820. };
  42821. Animation.prototype.getHighestFrame = function () {
  42822. var ret = 0;
  42823. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42824. if (ret < this._keys[key].frame) {
  42825. ret = this._keys[key].frame;
  42826. }
  42827. }
  42828. return ret;
  42829. };
  42830. Animation.prototype.getEasingFunction = function () {
  42831. return this._easingFunction;
  42832. };
  42833. Animation.prototype.setEasingFunction = function (easingFunction) {
  42834. this._easingFunction = easingFunction;
  42835. };
  42836. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42837. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42838. };
  42839. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42840. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42841. };
  42842. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42843. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42844. };
  42845. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42846. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42847. };
  42848. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42849. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42850. };
  42851. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42852. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42853. };
  42854. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42855. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42856. };
  42857. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42858. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42859. };
  42860. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42861. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42862. };
  42863. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42864. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42865. };
  42866. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42867. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42868. };
  42869. Animation.prototype.clone = function () {
  42870. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42871. clone.enableBlending = this.enableBlending;
  42872. clone.blendingSpeed = this.blendingSpeed;
  42873. if (this._keys) {
  42874. clone.setKeys(this._keys);
  42875. }
  42876. if (this._ranges) {
  42877. clone._ranges = {};
  42878. for (var name in this._ranges) {
  42879. var range = this._ranges[name];
  42880. if (!range) {
  42881. continue;
  42882. }
  42883. clone._ranges[name] = range.clone();
  42884. }
  42885. }
  42886. return clone;
  42887. };
  42888. Animation.prototype.setKeys = function (values) {
  42889. this._keys = values.slice(0);
  42890. };
  42891. Animation.prototype.serialize = function () {
  42892. var serializationObject = {};
  42893. serializationObject.name = this.name;
  42894. serializationObject.property = this.targetProperty;
  42895. serializationObject.framePerSecond = this.framePerSecond;
  42896. serializationObject.dataType = this.dataType;
  42897. serializationObject.loopBehavior = this.loopMode;
  42898. serializationObject.enableBlending = this.enableBlending;
  42899. serializationObject.blendingSpeed = this.blendingSpeed;
  42900. var dataType = this.dataType;
  42901. serializationObject.keys = [];
  42902. var keys = this.getKeys();
  42903. for (var index = 0; index < keys.length; index++) {
  42904. var animationKey = keys[index];
  42905. var key = {};
  42906. key.frame = animationKey.frame;
  42907. switch (dataType) {
  42908. case Animation.ANIMATIONTYPE_FLOAT:
  42909. key.values = [animationKey.value];
  42910. break;
  42911. case Animation.ANIMATIONTYPE_QUATERNION:
  42912. case Animation.ANIMATIONTYPE_MATRIX:
  42913. case Animation.ANIMATIONTYPE_VECTOR3:
  42914. case Animation.ANIMATIONTYPE_COLOR3:
  42915. key.values = animationKey.value.asArray();
  42916. break;
  42917. }
  42918. serializationObject.keys.push(key);
  42919. }
  42920. serializationObject.ranges = [];
  42921. for (var name in this._ranges) {
  42922. var source = this._ranges[name];
  42923. if (!source) {
  42924. continue;
  42925. }
  42926. var range = {};
  42927. range.name = name;
  42928. range.from = source.from;
  42929. range.to = source.to;
  42930. serializationObject.ranges.push(range);
  42931. }
  42932. return serializationObject;
  42933. };
  42934. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42935. get: function () {
  42936. return Animation._ANIMATIONTYPE_FLOAT;
  42937. },
  42938. enumerable: true,
  42939. configurable: true
  42940. });
  42941. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42942. get: function () {
  42943. return Animation._ANIMATIONTYPE_VECTOR3;
  42944. },
  42945. enumerable: true,
  42946. configurable: true
  42947. });
  42948. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42949. get: function () {
  42950. return Animation._ANIMATIONTYPE_VECTOR2;
  42951. },
  42952. enumerable: true,
  42953. configurable: true
  42954. });
  42955. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42956. get: function () {
  42957. return Animation._ANIMATIONTYPE_SIZE;
  42958. },
  42959. enumerable: true,
  42960. configurable: true
  42961. });
  42962. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42963. get: function () {
  42964. return Animation._ANIMATIONTYPE_QUATERNION;
  42965. },
  42966. enumerable: true,
  42967. configurable: true
  42968. });
  42969. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42970. get: function () {
  42971. return Animation._ANIMATIONTYPE_MATRIX;
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42977. get: function () {
  42978. return Animation._ANIMATIONTYPE_COLOR3;
  42979. },
  42980. enumerable: true,
  42981. configurable: true
  42982. });
  42983. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42984. get: function () {
  42985. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42991. get: function () {
  42992. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42993. },
  42994. enumerable: true,
  42995. configurable: true
  42996. });
  42997. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42998. get: function () {
  42999. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. Animation.Parse = function (parsedAnimation) {
  43005. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43006. var dataType = parsedAnimation.dataType;
  43007. var keys = [];
  43008. var data;
  43009. var index;
  43010. if (parsedAnimation.enableBlending) {
  43011. animation.enableBlending = parsedAnimation.enableBlending;
  43012. }
  43013. if (parsedAnimation.blendingSpeed) {
  43014. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43015. }
  43016. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43017. var key = parsedAnimation.keys[index];
  43018. var inTangent;
  43019. var outTangent;
  43020. switch (dataType) {
  43021. case Animation.ANIMATIONTYPE_FLOAT:
  43022. data = key.values[0];
  43023. if (key.values.length >= 1) {
  43024. inTangent = key.values[1];
  43025. }
  43026. if (key.values.length >= 2) {
  43027. outTangent = key.values[2];
  43028. }
  43029. break;
  43030. case Animation.ANIMATIONTYPE_QUATERNION:
  43031. data = BABYLON.Quaternion.FromArray(key.values);
  43032. if (key.values.length >= 8) {
  43033. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43034. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43035. inTangent = _inTangent;
  43036. }
  43037. }
  43038. if (key.values.length >= 12) {
  43039. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43040. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43041. outTangent = _outTangent;
  43042. }
  43043. }
  43044. break;
  43045. case Animation.ANIMATIONTYPE_MATRIX:
  43046. data = BABYLON.Matrix.FromArray(key.values);
  43047. break;
  43048. case Animation.ANIMATIONTYPE_COLOR3:
  43049. data = BABYLON.Color3.FromArray(key.values);
  43050. break;
  43051. case Animation.ANIMATIONTYPE_VECTOR3:
  43052. default:
  43053. data = BABYLON.Vector3.FromArray(key.values);
  43054. break;
  43055. }
  43056. var keyData = {};
  43057. keyData.frame = key.frame;
  43058. keyData.value = data;
  43059. if (inTangent != undefined) {
  43060. keyData.inTangent = inTangent;
  43061. }
  43062. if (outTangent != undefined) {
  43063. keyData.outTangent = outTangent;
  43064. }
  43065. keys.push(keyData);
  43066. }
  43067. animation.setKeys(keys);
  43068. if (parsedAnimation.ranges) {
  43069. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43070. data = parsedAnimation.ranges[index];
  43071. animation.createRange(data.name, data.from, data.to);
  43072. }
  43073. }
  43074. return animation;
  43075. };
  43076. Animation.AppendSerializedAnimations = function (source, destination) {
  43077. if (source.animations) {
  43078. destination.animations = [];
  43079. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43080. var animation = source.animations[animationIndex];
  43081. destination.animations.push(animation.serialize());
  43082. }
  43083. }
  43084. };
  43085. Animation.AllowMatricesInterpolation = false;
  43086. // Statics
  43087. Animation._ANIMATIONTYPE_FLOAT = 0;
  43088. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43089. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43090. Animation._ANIMATIONTYPE_MATRIX = 3;
  43091. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43092. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43093. Animation._ANIMATIONTYPE_SIZE = 6;
  43094. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43095. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43096. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43097. return Animation;
  43098. }());
  43099. BABYLON.Animation = Animation;
  43100. })(BABYLON || (BABYLON = {}));
  43101. //# sourceMappingURL=babylon.animation.js.map
  43102. var BABYLON;
  43103. (function (BABYLON) {
  43104. /**
  43105. * This class defines the direct association between an animation and a target
  43106. */
  43107. var TargetedAnimation = /** @class */ (function () {
  43108. function TargetedAnimation() {
  43109. }
  43110. return TargetedAnimation;
  43111. }());
  43112. BABYLON.TargetedAnimation = TargetedAnimation;
  43113. /**
  43114. * Use this class to create coordinated animations on multiple targets
  43115. */
  43116. var AnimationGroup = /** @class */ (function () {
  43117. function AnimationGroup(name, scene) {
  43118. if (scene === void 0) { scene = null; }
  43119. this.name = name;
  43120. this._targetedAnimations = new Array();
  43121. this._animatables = new Array();
  43122. this._from = Number.MAX_VALUE;
  43123. this._to = -Number.MAX_VALUE;
  43124. this._speedRatio = 1;
  43125. this.onAnimationEndObservable = new BABYLON.Observable();
  43126. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43127. this._scene.animationGroups.push(this);
  43128. }
  43129. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43130. /**
  43131. * Define if the animations are started
  43132. */
  43133. get: function () {
  43134. return this._isStarted;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43140. /**
  43141. * Gets or sets the speed ratio to use for all animations
  43142. */
  43143. get: function () {
  43144. return this._speedRatio;
  43145. },
  43146. /**
  43147. * Gets or sets the speed ratio to use for all animations
  43148. */
  43149. set: function (value) {
  43150. if (this._speedRatio === value) {
  43151. return;
  43152. }
  43153. this._speedRatio = value;
  43154. for (var index = 0; index < this._animatables.length; index++) {
  43155. var animatable = this._animatables[index];
  43156. animatable.speedRatio = this._speedRatio;
  43157. }
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43163. /**
  43164. * Gets the targeted animations for this animation group
  43165. */
  43166. get: function () {
  43167. return this._targetedAnimations;
  43168. },
  43169. enumerable: true,
  43170. configurable: true
  43171. });
  43172. /**
  43173. * Add an animation (with its target) in the group
  43174. * @param animation defines the animation we want to add
  43175. * @param target defines the target of the animation
  43176. * @returns the {BABYLON.TargetedAnimation} object
  43177. */
  43178. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43179. var targetedAnimation = {
  43180. animation: animation,
  43181. target: target
  43182. };
  43183. var keys = animation.getKeys();
  43184. if (this._from > keys[0].frame) {
  43185. this._from = keys[0].frame;
  43186. }
  43187. if (this._to < keys[keys.length - 1].frame) {
  43188. this._to = keys[keys.length - 1].frame;
  43189. }
  43190. this._targetedAnimations.push(targetedAnimation);
  43191. return targetedAnimation;
  43192. };
  43193. /**
  43194. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43195. * It can add constant keys at begin or end
  43196. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43197. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43198. */
  43199. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43200. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43201. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43202. beginFrame = Math.max(beginFrame, this._from);
  43203. endFrame = Math.min(endFrame, this._to);
  43204. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43205. var targetedAnimation = this._targetedAnimations[index];
  43206. var keys = targetedAnimation.animation.getKeys();
  43207. var startKey = keys[0];
  43208. var endKey = keys[keys.length - 1];
  43209. if (startKey.frame > beginFrame) {
  43210. var newKey = {
  43211. frame: beginFrame,
  43212. value: startKey.value,
  43213. inTangent: startKey.inTangent,
  43214. outTangent: startKey.outTangent,
  43215. interpolation: startKey.interpolation
  43216. };
  43217. keys.splice(0, 0, newKey);
  43218. }
  43219. if (endKey.frame < endFrame) {
  43220. var newKey = {
  43221. frame: endFrame,
  43222. value: endKey.value,
  43223. inTangent: endKey.outTangent,
  43224. outTangent: endKey.outTangent,
  43225. interpolation: endKey.interpolation
  43226. };
  43227. keys.push(newKey);
  43228. }
  43229. }
  43230. return this;
  43231. };
  43232. /**
  43233. * Start all animations on given targets
  43234. * @param loop defines if animations must loop
  43235. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43236. */
  43237. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43238. var _this = this;
  43239. if (loop === void 0) { loop = false; }
  43240. if (speedRatio === void 0) { speedRatio = 1; }
  43241. if (this._isStarted || this._targetedAnimations.length === 0) {
  43242. return this;
  43243. }
  43244. var _loop_1 = function () {
  43245. var targetedAnimation = this_1._targetedAnimations[index];
  43246. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43247. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43248. }));
  43249. };
  43250. var this_1 = this;
  43251. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43252. _loop_1();
  43253. }
  43254. this._speedRatio = speedRatio;
  43255. this._isStarted = true;
  43256. return this;
  43257. };
  43258. /**
  43259. * Pause all animations
  43260. */
  43261. AnimationGroup.prototype.pause = function () {
  43262. if (!this._isStarted) {
  43263. return this;
  43264. }
  43265. for (var index = 0; index < this._animatables.length; index++) {
  43266. var animatable = this._animatables[index];
  43267. animatable.pause();
  43268. }
  43269. return this;
  43270. };
  43271. /**
  43272. * Play all animations to initial state
  43273. * This function will start() the animations if they were not started or will restart() them if they were paused
  43274. * @param loop defines if animations must loop
  43275. */
  43276. AnimationGroup.prototype.play = function (loop) {
  43277. if (this.isStarted) {
  43278. if (loop !== undefined) {
  43279. for (var index = 0; index < this._animatables.length; index++) {
  43280. var animatable = this._animatables[index];
  43281. animatable.loopAnimation = loop;
  43282. }
  43283. }
  43284. this.restart();
  43285. }
  43286. else {
  43287. this.start(loop, this._speedRatio);
  43288. }
  43289. return this;
  43290. };
  43291. /**
  43292. * Reset all animations to initial state
  43293. */
  43294. AnimationGroup.prototype.reset = function () {
  43295. if (!this._isStarted) {
  43296. return this;
  43297. }
  43298. for (var index = 0; index < this._animatables.length; index++) {
  43299. var animatable = this._animatables[index];
  43300. animatable.reset();
  43301. }
  43302. return this;
  43303. };
  43304. /**
  43305. * Restart animations from key 0
  43306. */
  43307. AnimationGroup.prototype.restart = function () {
  43308. if (!this._isStarted) {
  43309. return this;
  43310. }
  43311. for (var index = 0; index < this._animatables.length; index++) {
  43312. var animatable = this._animatables[index];
  43313. animatable.restart();
  43314. }
  43315. return this;
  43316. };
  43317. /**
  43318. * Stop all animations
  43319. */
  43320. AnimationGroup.prototype.stop = function () {
  43321. if (!this._isStarted) {
  43322. return this;
  43323. }
  43324. for (var index = 0; index < this._animatables.length; index++) {
  43325. var animatable = this._animatables[index];
  43326. animatable.stop();
  43327. }
  43328. this._isStarted = false;
  43329. return this;
  43330. };
  43331. /**
  43332. * Dispose all associated resources
  43333. */
  43334. AnimationGroup.prototype.dispose = function () {
  43335. this._targetedAnimations = [];
  43336. this._animatables = [];
  43337. var index = this._scene.animationGroups.indexOf(this);
  43338. if (index > -1) {
  43339. this._scene.animationGroups.splice(index, 1);
  43340. }
  43341. };
  43342. return AnimationGroup;
  43343. }());
  43344. BABYLON.AnimationGroup = AnimationGroup;
  43345. })(BABYLON || (BABYLON = {}));
  43346. //# sourceMappingURL=babylon.animationGroup.js.map
  43347. var BABYLON;
  43348. (function (BABYLON) {
  43349. var RuntimeAnimation = /** @class */ (function () {
  43350. function RuntimeAnimation(target, animation) {
  43351. this._offsetsCache = {};
  43352. this._highLimitsCache = {};
  43353. this._stopped = false;
  43354. this._blendingFactor = 0;
  43355. this._ratioOffset = 0;
  43356. this._animation = animation;
  43357. this._target = target;
  43358. animation._runtimeAnimations.push(this);
  43359. }
  43360. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43361. get: function () {
  43362. return this._animation;
  43363. },
  43364. enumerable: true,
  43365. configurable: true
  43366. });
  43367. RuntimeAnimation.prototype.reset = function () {
  43368. this._offsetsCache = {};
  43369. this._highLimitsCache = {};
  43370. this.currentFrame = 0;
  43371. this._blendingFactor = 0;
  43372. this._originalBlendValue = null;
  43373. };
  43374. RuntimeAnimation.prototype.isStopped = function () {
  43375. return this._stopped;
  43376. };
  43377. RuntimeAnimation.prototype.dispose = function () {
  43378. var index = this._animation.runtimeAnimations.indexOf(this);
  43379. if (index > -1) {
  43380. this._animation.runtimeAnimations.splice(index, 1);
  43381. }
  43382. };
  43383. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43384. if (typeof value === "function") {
  43385. return value();
  43386. }
  43387. return value;
  43388. };
  43389. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43390. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43391. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43392. }
  43393. this.currentFrame = currentFrame;
  43394. var keys = this._animation.getKeys();
  43395. // Try to get a hash to find the right key
  43396. 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));
  43397. if (keys[startKeyIndex].frame >= currentFrame) {
  43398. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43399. startKeyIndex--;
  43400. }
  43401. }
  43402. for (var key = startKeyIndex; key < keys.length; key++) {
  43403. var endKey = keys[key + 1];
  43404. if (endKey.frame >= currentFrame) {
  43405. var startKey = keys[key];
  43406. var startValue = this._getKeyValue(startKey.value);
  43407. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43408. return startValue;
  43409. }
  43410. var endValue = this._getKeyValue(endKey.value);
  43411. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43412. var frameDelta = endKey.frame - startKey.frame;
  43413. // gradient : percent of currentFrame between the frame inf and the frame sup
  43414. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43415. // check for easingFunction and correction of gradient
  43416. var easingFunction = this._animation.getEasingFunction();
  43417. if (easingFunction != null) {
  43418. gradient = easingFunction.ease(gradient);
  43419. }
  43420. switch (this._animation.dataType) {
  43421. // Float
  43422. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43423. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43424. switch (loopMode) {
  43425. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43426. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43427. return floatValue;
  43428. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43429. return offsetValue * repeatCount + floatValue;
  43430. }
  43431. break;
  43432. // Quaternion
  43433. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43434. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43435. switch (loopMode) {
  43436. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43437. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43438. return quatValue;
  43439. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43440. return quatValue.add(offsetValue.scale(repeatCount));
  43441. }
  43442. return quatValue;
  43443. // Vector3
  43444. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43445. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43446. switch (loopMode) {
  43447. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43448. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43449. return vec3Value;
  43450. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43451. return vec3Value.add(offsetValue.scale(repeatCount));
  43452. }
  43453. // Vector2
  43454. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43455. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43456. switch (loopMode) {
  43457. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43458. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43459. return vec2Value;
  43460. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43461. return vec2Value.add(offsetValue.scale(repeatCount));
  43462. }
  43463. // Size
  43464. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43465. switch (loopMode) {
  43466. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43467. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43468. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43469. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43470. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43471. }
  43472. // Color3
  43473. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43474. switch (loopMode) {
  43475. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43476. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43477. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43478. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43479. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43480. }
  43481. // Matrix
  43482. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43483. switch (loopMode) {
  43484. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43485. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43486. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43487. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43488. }
  43489. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43490. return startValue;
  43491. }
  43492. default:
  43493. break;
  43494. }
  43495. break;
  43496. }
  43497. }
  43498. return this._getKeyValue(keys[keys.length - 1].value);
  43499. };
  43500. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43501. if (blend === void 0) { blend = false; }
  43502. // Set value
  43503. var path;
  43504. var destination;
  43505. var targetPropertyPath = this._animation.targetPropertyPath;
  43506. if (targetPropertyPath.length > 1) {
  43507. var property = this._target[targetPropertyPath[0]];
  43508. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  43509. property = property[targetPropertyPath[index]];
  43510. }
  43511. path = targetPropertyPath[targetPropertyPath.length - 1];
  43512. destination = property;
  43513. }
  43514. else {
  43515. path = targetPropertyPath[0];
  43516. destination = this._target;
  43517. }
  43518. // Blending
  43519. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  43520. if (!this._originalBlendValue) {
  43521. if (destination[path].clone) {
  43522. this._originalBlendValue = destination[path].clone();
  43523. }
  43524. else {
  43525. this._originalBlendValue = destination[path];
  43526. }
  43527. }
  43528. if (this._originalBlendValue.prototype) {
  43529. if (this._originalBlendValue.prototype.Lerp) {
  43530. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  43531. }
  43532. else {
  43533. destination[path] = currentValue;
  43534. }
  43535. }
  43536. else if (this._originalBlendValue.m) {
  43537. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  43538. }
  43539. else {
  43540. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  43541. }
  43542. this._blendingFactor += this._animation.blendingSpeed;
  43543. }
  43544. else {
  43545. destination[path] = currentValue;
  43546. }
  43547. if (this._target.markAsDirty) {
  43548. this._target.markAsDirty(this._animation.targetProperty);
  43549. }
  43550. };
  43551. RuntimeAnimation.prototype.goToFrame = function (frame) {
  43552. var keys = this._animation.getKeys();
  43553. if (frame < keys[0].frame) {
  43554. frame = keys[0].frame;
  43555. }
  43556. else if (frame > keys[keys.length - 1].frame) {
  43557. frame = keys[keys.length - 1].frame;
  43558. }
  43559. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  43560. this.setValue(currentValue);
  43561. };
  43562. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  43563. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  43564. this._ratioOffset = this._previousRatio - newRatio;
  43565. };
  43566. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  43567. if (blend === void 0) { blend = false; }
  43568. var targetPropertyPath = this._animation.targetPropertyPath;
  43569. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  43570. this._stopped = true;
  43571. return false;
  43572. }
  43573. var returnValue = true;
  43574. var keys = this._animation.getKeys();
  43575. // Adding a start key at frame 0 if missing
  43576. if (keys[0].frame !== 0) {
  43577. var newKey = { frame: 0, value: keys[0].value };
  43578. keys.splice(0, 0, newKey);
  43579. }
  43580. // Check limits
  43581. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  43582. from = keys[0].frame;
  43583. }
  43584. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  43585. to = keys[keys.length - 1].frame;
  43586. }
  43587. //to and from cannot be the same key
  43588. if (from === to) {
  43589. if (from > keys[0].frame) {
  43590. from--;
  43591. }
  43592. else if (to < keys[keys.length - 1].frame) {
  43593. to++;
  43594. }
  43595. }
  43596. // Compute ratio
  43597. var range = to - from;
  43598. var offsetValue;
  43599. // ratio represents the frame delta between from and to
  43600. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  43601. var highLimitValue = 0;
  43602. this._previousDelay = delay;
  43603. this._previousRatio = ratio;
  43604. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  43605. returnValue = false;
  43606. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  43607. }
  43608. else {
  43609. // Get max value if required
  43610. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  43611. var keyOffset = to.toString() + from.toString();
  43612. if (!this._offsetsCache[keyOffset]) {
  43613. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43614. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43615. switch (this._animation.dataType) {
  43616. // Float
  43617. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43618. this._offsetsCache[keyOffset] = toValue - fromValue;
  43619. break;
  43620. // Quaternion
  43621. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43622. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43623. break;
  43624. // Vector3
  43625. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43626. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43627. // Vector2
  43628. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43629. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43630. // Size
  43631. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43632. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43633. // Color3
  43634. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43635. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43636. default:
  43637. break;
  43638. }
  43639. this._highLimitsCache[keyOffset] = toValue;
  43640. }
  43641. highLimitValue = this._highLimitsCache[keyOffset];
  43642. offsetValue = this._offsetsCache[keyOffset];
  43643. }
  43644. }
  43645. if (offsetValue === undefined) {
  43646. switch (this._animation.dataType) {
  43647. // Float
  43648. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43649. offsetValue = 0;
  43650. break;
  43651. // Quaternion
  43652. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43653. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  43654. break;
  43655. // Vector3
  43656. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43657. offsetValue = BABYLON.Vector3.Zero();
  43658. break;
  43659. // Vector2
  43660. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43661. offsetValue = BABYLON.Vector2.Zero();
  43662. break;
  43663. // Size
  43664. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43665. offsetValue = BABYLON.Size.Zero();
  43666. break;
  43667. // Color3
  43668. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43669. offsetValue = BABYLON.Color3.Black();
  43670. }
  43671. }
  43672. // Compute value
  43673. var repeatCount = (ratio / range) >> 0;
  43674. var currentFrame = returnValue ? from + ratio % range : to;
  43675. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  43676. // Set value
  43677. this.setValue(currentValue);
  43678. // Check events
  43679. var events = this._animation.getEvents();
  43680. for (var index = 0; index < events.length; index++) {
  43681. // Make sure current frame has passed event frame and that event frame is within the current range
  43682. // Also, handle both forward and reverse animations
  43683. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  43684. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  43685. var event = events[index];
  43686. if (!event.isDone) {
  43687. // If event should be done only once, remove it.
  43688. if (event.onlyOnce) {
  43689. events.splice(index, 1);
  43690. index--;
  43691. }
  43692. event.isDone = true;
  43693. event.action();
  43694. } // Don't do anything if the event has already be done.
  43695. }
  43696. else if (events[index].isDone && !events[index].onlyOnce) {
  43697. // reset event, the animation is looping
  43698. events[index].isDone = false;
  43699. }
  43700. }
  43701. if (!returnValue) {
  43702. this._stopped = true;
  43703. }
  43704. return returnValue;
  43705. };
  43706. return RuntimeAnimation;
  43707. }());
  43708. BABYLON.RuntimeAnimation = RuntimeAnimation;
  43709. })(BABYLON || (BABYLON = {}));
  43710. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  43711. var BABYLON;
  43712. (function (BABYLON) {
  43713. var Animatable = /** @class */ (function () {
  43714. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  43715. if (fromFrame === void 0) { fromFrame = 0; }
  43716. if (toFrame === void 0) { toFrame = 100; }
  43717. if (loopAnimation === void 0) { loopAnimation = false; }
  43718. if (speedRatio === void 0) { speedRatio = 1.0; }
  43719. this.target = target;
  43720. this.fromFrame = fromFrame;
  43721. this.toFrame = toFrame;
  43722. this.loopAnimation = loopAnimation;
  43723. this.onAnimationEnd = onAnimationEnd;
  43724. this._localDelayOffset = null;
  43725. this._pausedDelay = null;
  43726. this._runtimeAnimations = new Array();
  43727. this._paused = false;
  43728. this._speedRatio = 1;
  43729. this.animationStarted = false;
  43730. if (animations) {
  43731. this.appendAnimations(target, animations);
  43732. }
  43733. this._speedRatio = speedRatio;
  43734. this._scene = scene;
  43735. scene._activeAnimatables.push(this);
  43736. }
  43737. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43738. get: function () {
  43739. return this._speedRatio;
  43740. },
  43741. set: function (value) {
  43742. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43743. var animation = this._runtimeAnimations[index];
  43744. animation._prepareForSpeedRatioChange(value);
  43745. }
  43746. this._speedRatio = value;
  43747. },
  43748. enumerable: true,
  43749. configurable: true
  43750. });
  43751. // Methods
  43752. Animatable.prototype.getAnimations = function () {
  43753. return this._runtimeAnimations;
  43754. };
  43755. Animatable.prototype.appendAnimations = function (target, animations) {
  43756. for (var index = 0; index < animations.length; index++) {
  43757. var animation = animations[index];
  43758. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43759. }
  43760. };
  43761. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43762. var runtimeAnimations = this._runtimeAnimations;
  43763. for (var index = 0; index < runtimeAnimations.length; index++) {
  43764. if (runtimeAnimations[index].animation.targetProperty === property) {
  43765. return runtimeAnimations[index].animation;
  43766. }
  43767. }
  43768. return null;
  43769. };
  43770. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43771. var runtimeAnimations = this._runtimeAnimations;
  43772. for (var index = 0; index < runtimeAnimations.length; index++) {
  43773. if (runtimeAnimations[index].animation.targetProperty === property) {
  43774. return runtimeAnimations[index];
  43775. }
  43776. }
  43777. return null;
  43778. };
  43779. Animatable.prototype.reset = function () {
  43780. var runtimeAnimations = this._runtimeAnimations;
  43781. for (var index = 0; index < runtimeAnimations.length; index++) {
  43782. runtimeAnimations[index].reset();
  43783. }
  43784. // Reset to original value
  43785. for (index = 0; index < runtimeAnimations.length; index++) {
  43786. var animation = runtimeAnimations[index];
  43787. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43788. }
  43789. this._localDelayOffset = null;
  43790. this._pausedDelay = null;
  43791. };
  43792. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43793. var runtimeAnimations = this._runtimeAnimations;
  43794. for (var index = 0; index < runtimeAnimations.length; index++) {
  43795. runtimeAnimations[index].animation.enableBlending = true;
  43796. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43797. }
  43798. };
  43799. Animatable.prototype.disableBlending = function () {
  43800. var runtimeAnimations = this._runtimeAnimations;
  43801. for (var index = 0; index < runtimeAnimations.length; index++) {
  43802. runtimeAnimations[index].animation.enableBlending = false;
  43803. }
  43804. };
  43805. Animatable.prototype.goToFrame = function (frame) {
  43806. var runtimeAnimations = this._runtimeAnimations;
  43807. if (runtimeAnimations[0]) {
  43808. var fps = runtimeAnimations[0].animation.framePerSecond;
  43809. var currentFrame = runtimeAnimations[0].currentFrame;
  43810. var adjustTime = frame - currentFrame;
  43811. var delay = adjustTime * 1000 / fps;
  43812. if (this._localDelayOffset === null) {
  43813. this._localDelayOffset = 0;
  43814. }
  43815. this._localDelayOffset -= delay;
  43816. }
  43817. for (var index = 0; index < runtimeAnimations.length; index++) {
  43818. runtimeAnimations[index].goToFrame(frame);
  43819. }
  43820. };
  43821. Animatable.prototype.pause = function () {
  43822. if (this._paused) {
  43823. return;
  43824. }
  43825. this._paused = true;
  43826. };
  43827. Animatable.prototype.restart = function () {
  43828. this._paused = false;
  43829. };
  43830. Animatable.prototype.stop = function (animationName) {
  43831. if (animationName) {
  43832. var idx = this._scene._activeAnimatables.indexOf(this);
  43833. if (idx > -1) {
  43834. var runtimeAnimations = this._runtimeAnimations;
  43835. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43836. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43837. continue;
  43838. }
  43839. runtimeAnimations[index].dispose();
  43840. runtimeAnimations.splice(index, 1);
  43841. }
  43842. if (runtimeAnimations.length == 0) {
  43843. this._scene._activeAnimatables.splice(idx, 1);
  43844. if (this.onAnimationEnd) {
  43845. this.onAnimationEnd();
  43846. }
  43847. }
  43848. }
  43849. }
  43850. else {
  43851. var index = this._scene._activeAnimatables.indexOf(this);
  43852. if (index > -1) {
  43853. this._scene._activeAnimatables.splice(index, 1);
  43854. var runtimeAnimations = this._runtimeAnimations;
  43855. for (var index = 0; index < runtimeAnimations.length; index++) {
  43856. runtimeAnimations[index].dispose();
  43857. }
  43858. if (this.onAnimationEnd) {
  43859. this.onAnimationEnd();
  43860. }
  43861. }
  43862. }
  43863. };
  43864. Animatable.prototype._animate = function (delay) {
  43865. if (this._paused) {
  43866. this.animationStarted = false;
  43867. if (this._pausedDelay === null) {
  43868. this._pausedDelay = delay;
  43869. }
  43870. return true;
  43871. }
  43872. if (this._localDelayOffset === null) {
  43873. this._localDelayOffset = delay;
  43874. }
  43875. else if (this._pausedDelay !== null) {
  43876. this._localDelayOffset += delay - this._pausedDelay;
  43877. this._pausedDelay = null;
  43878. }
  43879. // Animating
  43880. var running = false;
  43881. var runtimeAnimations = this._runtimeAnimations;
  43882. var index;
  43883. for (index = 0; index < runtimeAnimations.length; index++) {
  43884. var animation = runtimeAnimations[index];
  43885. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43886. running = running || isRunning;
  43887. }
  43888. this.animationStarted = running;
  43889. if (!running) {
  43890. // Remove from active animatables
  43891. index = this._scene._activeAnimatables.indexOf(this);
  43892. this._scene._activeAnimatables.splice(index, 1);
  43893. // Dispose all runtime animations
  43894. for (index = 0; index < runtimeAnimations.length; index++) {
  43895. runtimeAnimations[index].dispose();
  43896. }
  43897. }
  43898. if (!running && this.onAnimationEnd) {
  43899. this.onAnimationEnd();
  43900. this.onAnimationEnd = null;
  43901. }
  43902. return running;
  43903. };
  43904. return Animatable;
  43905. }());
  43906. BABYLON.Animatable = Animatable;
  43907. })(BABYLON || (BABYLON = {}));
  43908. //# sourceMappingURL=babylon.animatable.js.map
  43909. var BABYLON;
  43910. (function (BABYLON) {
  43911. var EasingFunction = /** @class */ (function () {
  43912. function EasingFunction() {
  43913. // Properties
  43914. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43915. }
  43916. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43917. get: function () {
  43918. return EasingFunction._EASINGMODE_EASEIN;
  43919. },
  43920. enumerable: true,
  43921. configurable: true
  43922. });
  43923. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43924. get: function () {
  43925. return EasingFunction._EASINGMODE_EASEOUT;
  43926. },
  43927. enumerable: true,
  43928. configurable: true
  43929. });
  43930. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43931. get: function () {
  43932. return EasingFunction._EASINGMODE_EASEINOUT;
  43933. },
  43934. enumerable: true,
  43935. configurable: true
  43936. });
  43937. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43938. var n = Math.min(Math.max(easingMode, 0), 2);
  43939. this._easingMode = n;
  43940. };
  43941. EasingFunction.prototype.getEasingMode = function () {
  43942. return this._easingMode;
  43943. };
  43944. EasingFunction.prototype.easeInCore = function (gradient) {
  43945. throw new Error('You must implement this method');
  43946. };
  43947. EasingFunction.prototype.ease = function (gradient) {
  43948. switch (this._easingMode) {
  43949. case EasingFunction.EASINGMODE_EASEIN:
  43950. return this.easeInCore(gradient);
  43951. case EasingFunction.EASINGMODE_EASEOUT:
  43952. return (1 - this.easeInCore(1 - gradient));
  43953. }
  43954. if (gradient >= 0.5) {
  43955. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43956. }
  43957. return (this.easeInCore(gradient * 2) * 0.5);
  43958. };
  43959. //Statics
  43960. EasingFunction._EASINGMODE_EASEIN = 0;
  43961. EasingFunction._EASINGMODE_EASEOUT = 1;
  43962. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43963. return EasingFunction;
  43964. }());
  43965. BABYLON.EasingFunction = EasingFunction;
  43966. var CircleEase = /** @class */ (function (_super) {
  43967. __extends(CircleEase, _super);
  43968. function CircleEase() {
  43969. return _super !== null && _super.apply(this, arguments) || this;
  43970. }
  43971. CircleEase.prototype.easeInCore = function (gradient) {
  43972. gradient = Math.max(0, Math.min(1, gradient));
  43973. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43974. };
  43975. return CircleEase;
  43976. }(EasingFunction));
  43977. BABYLON.CircleEase = CircleEase;
  43978. var BackEase = /** @class */ (function (_super) {
  43979. __extends(BackEase, _super);
  43980. function BackEase(amplitude) {
  43981. if (amplitude === void 0) { amplitude = 1; }
  43982. var _this = _super.call(this) || this;
  43983. _this.amplitude = amplitude;
  43984. return _this;
  43985. }
  43986. BackEase.prototype.easeInCore = function (gradient) {
  43987. var num = Math.max(0, this.amplitude);
  43988. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43989. };
  43990. return BackEase;
  43991. }(EasingFunction));
  43992. BABYLON.BackEase = BackEase;
  43993. var BounceEase = /** @class */ (function (_super) {
  43994. __extends(BounceEase, _super);
  43995. function BounceEase(bounces, bounciness) {
  43996. if (bounces === void 0) { bounces = 3; }
  43997. if (bounciness === void 0) { bounciness = 2; }
  43998. var _this = _super.call(this) || this;
  43999. _this.bounces = bounces;
  44000. _this.bounciness = bounciness;
  44001. return _this;
  44002. }
  44003. BounceEase.prototype.easeInCore = function (gradient) {
  44004. var y = Math.max(0.0, this.bounces);
  44005. var bounciness = this.bounciness;
  44006. if (bounciness <= 1.0) {
  44007. bounciness = 1.001;
  44008. }
  44009. var num9 = Math.pow(bounciness, y);
  44010. var num5 = 1.0 - bounciness;
  44011. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44012. var num15 = gradient * num4;
  44013. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44014. var num3 = Math.floor(num65);
  44015. var num13 = num3 + 1.0;
  44016. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44017. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44018. var num7 = (num8 + num12) * 0.5;
  44019. var num6 = gradient - num7;
  44020. var num2 = num7 - num8;
  44021. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44022. };
  44023. return BounceEase;
  44024. }(EasingFunction));
  44025. BABYLON.BounceEase = BounceEase;
  44026. var CubicEase = /** @class */ (function (_super) {
  44027. __extends(CubicEase, _super);
  44028. function CubicEase() {
  44029. return _super !== null && _super.apply(this, arguments) || this;
  44030. }
  44031. CubicEase.prototype.easeInCore = function (gradient) {
  44032. return (gradient * gradient * gradient);
  44033. };
  44034. return CubicEase;
  44035. }(EasingFunction));
  44036. BABYLON.CubicEase = CubicEase;
  44037. var ElasticEase = /** @class */ (function (_super) {
  44038. __extends(ElasticEase, _super);
  44039. function ElasticEase(oscillations, springiness) {
  44040. if (oscillations === void 0) { oscillations = 3; }
  44041. if (springiness === void 0) { springiness = 3; }
  44042. var _this = _super.call(this) || this;
  44043. _this.oscillations = oscillations;
  44044. _this.springiness = springiness;
  44045. return _this;
  44046. }
  44047. ElasticEase.prototype.easeInCore = function (gradient) {
  44048. var num2;
  44049. var num3 = Math.max(0.0, this.oscillations);
  44050. var num = Math.max(0.0, this.springiness);
  44051. if (num == 0) {
  44052. num2 = gradient;
  44053. }
  44054. else {
  44055. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44056. }
  44057. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44058. };
  44059. return ElasticEase;
  44060. }(EasingFunction));
  44061. BABYLON.ElasticEase = ElasticEase;
  44062. var ExponentialEase = /** @class */ (function (_super) {
  44063. __extends(ExponentialEase, _super);
  44064. function ExponentialEase(exponent) {
  44065. if (exponent === void 0) { exponent = 2; }
  44066. var _this = _super.call(this) || this;
  44067. _this.exponent = exponent;
  44068. return _this;
  44069. }
  44070. ExponentialEase.prototype.easeInCore = function (gradient) {
  44071. if (this.exponent <= 0) {
  44072. return gradient;
  44073. }
  44074. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44075. };
  44076. return ExponentialEase;
  44077. }(EasingFunction));
  44078. BABYLON.ExponentialEase = ExponentialEase;
  44079. var PowerEase = /** @class */ (function (_super) {
  44080. __extends(PowerEase, _super);
  44081. function PowerEase(power) {
  44082. if (power === void 0) { power = 2; }
  44083. var _this = _super.call(this) || this;
  44084. _this.power = power;
  44085. return _this;
  44086. }
  44087. PowerEase.prototype.easeInCore = function (gradient) {
  44088. var y = Math.max(0.0, this.power);
  44089. return Math.pow(gradient, y);
  44090. };
  44091. return PowerEase;
  44092. }(EasingFunction));
  44093. BABYLON.PowerEase = PowerEase;
  44094. var QuadraticEase = /** @class */ (function (_super) {
  44095. __extends(QuadraticEase, _super);
  44096. function QuadraticEase() {
  44097. return _super !== null && _super.apply(this, arguments) || this;
  44098. }
  44099. QuadraticEase.prototype.easeInCore = function (gradient) {
  44100. return (gradient * gradient);
  44101. };
  44102. return QuadraticEase;
  44103. }(EasingFunction));
  44104. BABYLON.QuadraticEase = QuadraticEase;
  44105. var QuarticEase = /** @class */ (function (_super) {
  44106. __extends(QuarticEase, _super);
  44107. function QuarticEase() {
  44108. return _super !== null && _super.apply(this, arguments) || this;
  44109. }
  44110. QuarticEase.prototype.easeInCore = function (gradient) {
  44111. return (gradient * gradient * gradient * gradient);
  44112. };
  44113. return QuarticEase;
  44114. }(EasingFunction));
  44115. BABYLON.QuarticEase = QuarticEase;
  44116. var QuinticEase = /** @class */ (function (_super) {
  44117. __extends(QuinticEase, _super);
  44118. function QuinticEase() {
  44119. return _super !== null && _super.apply(this, arguments) || this;
  44120. }
  44121. QuinticEase.prototype.easeInCore = function (gradient) {
  44122. return (gradient * gradient * gradient * gradient * gradient);
  44123. };
  44124. return QuinticEase;
  44125. }(EasingFunction));
  44126. BABYLON.QuinticEase = QuinticEase;
  44127. var SineEase = /** @class */ (function (_super) {
  44128. __extends(SineEase, _super);
  44129. function SineEase() {
  44130. return _super !== null && _super.apply(this, arguments) || this;
  44131. }
  44132. SineEase.prototype.easeInCore = function (gradient) {
  44133. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44134. };
  44135. return SineEase;
  44136. }(EasingFunction));
  44137. BABYLON.SineEase = SineEase;
  44138. var BezierCurveEase = /** @class */ (function (_super) {
  44139. __extends(BezierCurveEase, _super);
  44140. function BezierCurveEase(x1, y1, x2, y2) {
  44141. if (x1 === void 0) { x1 = 0; }
  44142. if (y1 === void 0) { y1 = 0; }
  44143. if (x2 === void 0) { x2 = 1; }
  44144. if (y2 === void 0) { y2 = 1; }
  44145. var _this = _super.call(this) || this;
  44146. _this.x1 = x1;
  44147. _this.y1 = y1;
  44148. _this.x2 = x2;
  44149. _this.y2 = y2;
  44150. return _this;
  44151. }
  44152. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44153. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44154. };
  44155. return BezierCurveEase;
  44156. }(EasingFunction));
  44157. BABYLON.BezierCurveEase = BezierCurveEase;
  44158. })(BABYLON || (BABYLON = {}));
  44159. //# sourceMappingURL=babylon.easing.js.map
  44160. var BABYLON;
  44161. (function (BABYLON) {
  44162. var Condition = /** @class */ (function () {
  44163. function Condition(actionManager) {
  44164. this._actionManager = actionManager;
  44165. }
  44166. Condition.prototype.isValid = function () {
  44167. return true;
  44168. };
  44169. Condition.prototype._getProperty = function (propertyPath) {
  44170. return this._actionManager._getProperty(propertyPath);
  44171. };
  44172. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44173. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44174. };
  44175. Condition.prototype.serialize = function () {
  44176. };
  44177. Condition.prototype._serialize = function (serializedCondition) {
  44178. return {
  44179. type: 2,
  44180. children: [],
  44181. name: serializedCondition.name,
  44182. properties: serializedCondition.properties
  44183. };
  44184. };
  44185. return Condition;
  44186. }());
  44187. BABYLON.Condition = Condition;
  44188. var ValueCondition = /** @class */ (function (_super) {
  44189. __extends(ValueCondition, _super);
  44190. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44191. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44192. var _this = _super.call(this, actionManager) || this;
  44193. _this.propertyPath = propertyPath;
  44194. _this.value = value;
  44195. _this.operator = operator;
  44196. _this._target = target;
  44197. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44198. _this._property = _this._getProperty(_this.propertyPath);
  44199. return _this;
  44200. }
  44201. Object.defineProperty(ValueCondition, "IsEqual", {
  44202. get: function () {
  44203. return ValueCondition._IsEqual;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(ValueCondition, "IsDifferent", {
  44209. get: function () {
  44210. return ValueCondition._IsDifferent;
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Object.defineProperty(ValueCondition, "IsGreater", {
  44216. get: function () {
  44217. return ValueCondition._IsGreater;
  44218. },
  44219. enumerable: true,
  44220. configurable: true
  44221. });
  44222. Object.defineProperty(ValueCondition, "IsLesser", {
  44223. get: function () {
  44224. return ValueCondition._IsLesser;
  44225. },
  44226. enumerable: true,
  44227. configurable: true
  44228. });
  44229. // Methods
  44230. ValueCondition.prototype.isValid = function () {
  44231. switch (this.operator) {
  44232. case ValueCondition.IsGreater:
  44233. return this._effectiveTarget[this._property] > this.value;
  44234. case ValueCondition.IsLesser:
  44235. return this._effectiveTarget[this._property] < this.value;
  44236. case ValueCondition.IsEqual:
  44237. case ValueCondition.IsDifferent:
  44238. var check;
  44239. if (this.value.equals) {
  44240. check = this.value.equals(this._effectiveTarget[this._property]);
  44241. }
  44242. else {
  44243. check = this.value === this._effectiveTarget[this._property];
  44244. }
  44245. return this.operator === ValueCondition.IsEqual ? check : !check;
  44246. }
  44247. return false;
  44248. };
  44249. ValueCondition.prototype.serialize = function () {
  44250. return this._serialize({
  44251. name: "ValueCondition",
  44252. properties: [
  44253. BABYLON.Action._GetTargetProperty(this._target),
  44254. { name: "propertyPath", value: this.propertyPath },
  44255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44256. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44257. ]
  44258. });
  44259. };
  44260. ValueCondition.GetOperatorName = function (operator) {
  44261. switch (operator) {
  44262. case ValueCondition._IsEqual: return "IsEqual";
  44263. case ValueCondition._IsDifferent: return "IsDifferent";
  44264. case ValueCondition._IsGreater: return "IsGreater";
  44265. case ValueCondition._IsLesser: return "IsLesser";
  44266. default: return "";
  44267. }
  44268. };
  44269. // Statics
  44270. ValueCondition._IsEqual = 0;
  44271. ValueCondition._IsDifferent = 1;
  44272. ValueCondition._IsGreater = 2;
  44273. ValueCondition._IsLesser = 3;
  44274. return ValueCondition;
  44275. }(Condition));
  44276. BABYLON.ValueCondition = ValueCondition;
  44277. var PredicateCondition = /** @class */ (function (_super) {
  44278. __extends(PredicateCondition, _super);
  44279. function PredicateCondition(actionManager, predicate) {
  44280. var _this = _super.call(this, actionManager) || this;
  44281. _this.predicate = predicate;
  44282. return _this;
  44283. }
  44284. PredicateCondition.prototype.isValid = function () {
  44285. return this.predicate();
  44286. };
  44287. return PredicateCondition;
  44288. }(Condition));
  44289. BABYLON.PredicateCondition = PredicateCondition;
  44290. var StateCondition = /** @class */ (function (_super) {
  44291. __extends(StateCondition, _super);
  44292. function StateCondition(actionManager, target, value) {
  44293. var _this = _super.call(this, actionManager) || this;
  44294. _this.value = value;
  44295. _this._target = target;
  44296. return _this;
  44297. }
  44298. // Methods
  44299. StateCondition.prototype.isValid = function () {
  44300. return this._target.state === this.value;
  44301. };
  44302. StateCondition.prototype.serialize = function () {
  44303. return this._serialize({
  44304. name: "StateCondition",
  44305. properties: [
  44306. BABYLON.Action._GetTargetProperty(this._target),
  44307. { name: "value", value: this.value }
  44308. ]
  44309. });
  44310. };
  44311. return StateCondition;
  44312. }(Condition));
  44313. BABYLON.StateCondition = StateCondition;
  44314. })(BABYLON || (BABYLON = {}));
  44315. //# sourceMappingURL=babylon.condition.js.map
  44316. var BABYLON;
  44317. (function (BABYLON) {
  44318. var Action = /** @class */ (function () {
  44319. function Action(triggerOptions, condition) {
  44320. this.triggerOptions = triggerOptions;
  44321. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44322. if (triggerOptions.parameter) {
  44323. this.trigger = triggerOptions.trigger;
  44324. this._triggerParameter = triggerOptions.parameter;
  44325. }
  44326. else {
  44327. this.trigger = triggerOptions;
  44328. }
  44329. this._nextActiveAction = this;
  44330. this._condition = condition;
  44331. }
  44332. // Methods
  44333. Action.prototype._prepare = function () {
  44334. };
  44335. Action.prototype.getTriggerParameter = function () {
  44336. return this._triggerParameter;
  44337. };
  44338. Action.prototype._executeCurrent = function (evt) {
  44339. if (this._nextActiveAction._condition) {
  44340. var condition = this._nextActiveAction._condition;
  44341. var currentRenderId = this._actionManager.getScene().getRenderId();
  44342. // We cache the current evaluation for the current frame
  44343. if (condition._evaluationId === currentRenderId) {
  44344. if (!condition._currentResult) {
  44345. return;
  44346. }
  44347. }
  44348. else {
  44349. condition._evaluationId = currentRenderId;
  44350. if (!condition.isValid()) {
  44351. condition._currentResult = false;
  44352. return;
  44353. }
  44354. condition._currentResult = true;
  44355. }
  44356. }
  44357. this.onBeforeExecuteObservable.notifyObservers(this);
  44358. this._nextActiveAction.execute(evt);
  44359. this.skipToNextActiveAction();
  44360. };
  44361. Action.prototype.execute = function (evt) {
  44362. };
  44363. Action.prototype.skipToNextActiveAction = function () {
  44364. if (this._nextActiveAction._child) {
  44365. if (!this._nextActiveAction._child._actionManager) {
  44366. this._nextActiveAction._child._actionManager = this._actionManager;
  44367. }
  44368. this._nextActiveAction = this._nextActiveAction._child;
  44369. }
  44370. else {
  44371. this._nextActiveAction = this;
  44372. }
  44373. };
  44374. Action.prototype.then = function (action) {
  44375. this._child = action;
  44376. action._actionManager = this._actionManager;
  44377. action._prepare();
  44378. return action;
  44379. };
  44380. Action.prototype._getProperty = function (propertyPath) {
  44381. return this._actionManager._getProperty(propertyPath);
  44382. };
  44383. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44384. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44385. };
  44386. Action.prototype.serialize = function (parent) {
  44387. };
  44388. // Called by BABYLON.Action objects in serialize(...). Internal use
  44389. Action.prototype._serialize = function (serializedAction, parent) {
  44390. var serializationObject = {
  44391. type: 1,
  44392. children: [],
  44393. name: serializedAction.name,
  44394. properties: serializedAction.properties || []
  44395. };
  44396. // Serialize child
  44397. if (this._child) {
  44398. this._child.serialize(serializationObject);
  44399. }
  44400. // Check if "this" has a condition
  44401. if (this._condition) {
  44402. var serializedCondition = this._condition.serialize();
  44403. serializedCondition.children.push(serializationObject);
  44404. if (parent) {
  44405. parent.children.push(serializedCondition);
  44406. }
  44407. return serializedCondition;
  44408. }
  44409. if (parent) {
  44410. parent.children.push(serializationObject);
  44411. }
  44412. return serializationObject;
  44413. };
  44414. Action._SerializeValueAsString = function (value) {
  44415. if (typeof value === "number") {
  44416. return value.toString();
  44417. }
  44418. if (typeof value === "boolean") {
  44419. return value ? "true" : "false";
  44420. }
  44421. if (value instanceof BABYLON.Vector2) {
  44422. return value.x + ", " + value.y;
  44423. }
  44424. if (value instanceof BABYLON.Vector3) {
  44425. return value.x + ", " + value.y + ", " + value.z;
  44426. }
  44427. if (value instanceof BABYLON.Color3) {
  44428. return value.r + ", " + value.g + ", " + value.b;
  44429. }
  44430. if (value instanceof BABYLON.Color4) {
  44431. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44432. }
  44433. return value; // string
  44434. };
  44435. Action._GetTargetProperty = function (target) {
  44436. return {
  44437. name: "target",
  44438. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44439. : target instanceof BABYLON.Light ? "LightProperties"
  44440. : target instanceof BABYLON.Camera ? "CameraProperties"
  44441. : "SceneProperties",
  44442. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44443. };
  44444. };
  44445. return Action;
  44446. }());
  44447. BABYLON.Action = Action;
  44448. })(BABYLON || (BABYLON = {}));
  44449. //# sourceMappingURL=babylon.action.js.map
  44450. var BABYLON;
  44451. (function (BABYLON) {
  44452. /**
  44453. * ActionEvent is the event beint sent when an action is triggered.
  44454. */
  44455. var ActionEvent = /** @class */ (function () {
  44456. /**
  44457. * @param source The mesh or sprite that triggered the action.
  44458. * @param pointerX The X mouse cursor position at the time of the event
  44459. * @param pointerY The Y mouse cursor position at the time of the event
  44460. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44461. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44462. */
  44463. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44464. this.source = source;
  44465. this.pointerX = pointerX;
  44466. this.pointerY = pointerY;
  44467. this.meshUnderPointer = meshUnderPointer;
  44468. this.sourceEvent = sourceEvent;
  44469. this.additionalData = additionalData;
  44470. }
  44471. /**
  44472. * Helper function to auto-create an ActionEvent from a source mesh.
  44473. * @param source The source mesh that triggered the event
  44474. * @param evt {Event} The original (browser) event
  44475. */
  44476. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44477. var scene = source.getScene();
  44478. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44479. };
  44480. /**
  44481. * Helper function to auto-create an ActionEvent from a source mesh.
  44482. * @param source The source sprite that triggered the event
  44483. * @param scene Scene associated with the sprite
  44484. * @param evt {Event} The original (browser) event
  44485. */
  44486. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44487. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44488. };
  44489. /**
  44490. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44491. * @param scene the scene where the event occurred
  44492. * @param evt {Event} The original (browser) event
  44493. */
  44494. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44495. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44496. };
  44497. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44498. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44499. };
  44500. return ActionEvent;
  44501. }());
  44502. BABYLON.ActionEvent = ActionEvent;
  44503. /**
  44504. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44505. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44506. */
  44507. var ActionManager = /** @class */ (function () {
  44508. function ActionManager(scene) {
  44509. // Members
  44510. this.actions = new Array();
  44511. this.hoverCursor = '';
  44512. this._scene = scene;
  44513. scene._actionManagers.push(this);
  44514. }
  44515. Object.defineProperty(ActionManager, "NothingTrigger", {
  44516. get: function () {
  44517. return ActionManager._NothingTrigger;
  44518. },
  44519. enumerable: true,
  44520. configurable: true
  44521. });
  44522. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44523. get: function () {
  44524. return ActionManager._OnPickTrigger;
  44525. },
  44526. enumerable: true,
  44527. configurable: true
  44528. });
  44529. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44530. get: function () {
  44531. return ActionManager._OnLeftPickTrigger;
  44532. },
  44533. enumerable: true,
  44534. configurable: true
  44535. });
  44536. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44537. get: function () {
  44538. return ActionManager._OnRightPickTrigger;
  44539. },
  44540. enumerable: true,
  44541. configurable: true
  44542. });
  44543. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44544. get: function () {
  44545. return ActionManager._OnCenterPickTrigger;
  44546. },
  44547. enumerable: true,
  44548. configurable: true
  44549. });
  44550. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44551. get: function () {
  44552. return ActionManager._OnPickDownTrigger;
  44553. },
  44554. enumerable: true,
  44555. configurable: true
  44556. });
  44557. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44558. get: function () {
  44559. return ActionManager._OnDoublePickTrigger;
  44560. },
  44561. enumerable: true,
  44562. configurable: true
  44563. });
  44564. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44565. get: function () {
  44566. return ActionManager._OnPickUpTrigger;
  44567. },
  44568. enumerable: true,
  44569. configurable: true
  44570. });
  44571. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  44572. /// This trigger will only be raised if you also declared a OnPickDown
  44573. get: function () {
  44574. return ActionManager._OnPickOutTrigger;
  44575. },
  44576. enumerable: true,
  44577. configurable: true
  44578. });
  44579. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  44580. get: function () {
  44581. return ActionManager._OnLongPressTrigger;
  44582. },
  44583. enumerable: true,
  44584. configurable: true
  44585. });
  44586. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  44587. get: function () {
  44588. return ActionManager._OnPointerOverTrigger;
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  44594. get: function () {
  44595. return ActionManager._OnPointerOutTrigger;
  44596. },
  44597. enumerable: true,
  44598. configurable: true
  44599. });
  44600. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44601. get: function () {
  44602. return ActionManager._OnEveryFrameTrigger;
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44608. get: function () {
  44609. return ActionManager._OnIntersectionEnterTrigger;
  44610. },
  44611. enumerable: true,
  44612. configurable: true
  44613. });
  44614. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44615. get: function () {
  44616. return ActionManager._OnIntersectionExitTrigger;
  44617. },
  44618. enumerable: true,
  44619. configurable: true
  44620. });
  44621. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44622. get: function () {
  44623. return ActionManager._OnKeyDownTrigger;
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  44629. get: function () {
  44630. return ActionManager._OnKeyUpTrigger;
  44631. },
  44632. enumerable: true,
  44633. configurable: true
  44634. });
  44635. // Methods
  44636. ActionManager.prototype.dispose = function () {
  44637. var index = this._scene._actionManagers.indexOf(this);
  44638. for (var i = 0; i < this.actions.length; i++) {
  44639. var action = this.actions[i];
  44640. ActionManager.Triggers[action.trigger]--;
  44641. if (ActionManager.Triggers[action.trigger] === 0) {
  44642. delete ActionManager.Triggers[action.trigger];
  44643. }
  44644. }
  44645. if (index > -1) {
  44646. this._scene._actionManagers.splice(index, 1);
  44647. }
  44648. };
  44649. ActionManager.prototype.getScene = function () {
  44650. return this._scene;
  44651. };
  44652. /**
  44653. * Does this action manager handles actions of any of the given triggers
  44654. * @param {number[]} triggers - the triggers to be tested
  44655. * @return {boolean} whether one (or more) of the triggers is handeled
  44656. */
  44657. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  44658. for (var index = 0; index < this.actions.length; index++) {
  44659. var action = this.actions[index];
  44660. if (triggers.indexOf(action.trigger) > -1) {
  44661. return true;
  44662. }
  44663. }
  44664. return false;
  44665. };
  44666. /**
  44667. * Does this action manager handles actions of a given trigger
  44668. * @param {number} trigger - the trigger to be tested
  44669. * @return {boolean} whether the trigger is handeled
  44670. */
  44671. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  44672. for (var index = 0; index < this.actions.length; index++) {
  44673. var action = this.actions[index];
  44674. if (action.trigger === trigger) {
  44675. return true;
  44676. }
  44677. }
  44678. return false;
  44679. };
  44680. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  44681. /**
  44682. * Does this action manager has pointer triggers
  44683. * @return {boolean} whether or not it has pointer triggers
  44684. */
  44685. get: function () {
  44686. for (var index = 0; index < this.actions.length; index++) {
  44687. var action = this.actions[index];
  44688. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  44689. return true;
  44690. }
  44691. }
  44692. return false;
  44693. },
  44694. enumerable: true,
  44695. configurable: true
  44696. });
  44697. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  44698. /**
  44699. * Does this action manager has pick triggers
  44700. * @return {boolean} whether or not it has pick triggers
  44701. */
  44702. get: function () {
  44703. for (var index = 0; index < this.actions.length; index++) {
  44704. var action = this.actions[index];
  44705. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44706. return true;
  44707. }
  44708. }
  44709. return false;
  44710. },
  44711. enumerable: true,
  44712. configurable: true
  44713. });
  44714. Object.defineProperty(ActionManager, "HasTriggers", {
  44715. /**
  44716. * Does exist one action manager with at least one trigger
  44717. * @return {boolean} whether or not it exists one action manager with one trigger
  44718. **/
  44719. get: function () {
  44720. for (var t in ActionManager.Triggers) {
  44721. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44722. return true;
  44723. }
  44724. }
  44725. return false;
  44726. },
  44727. enumerable: true,
  44728. configurable: true
  44729. });
  44730. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44731. /**
  44732. * Does exist one action manager with at least one pick trigger
  44733. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44734. **/
  44735. get: function () {
  44736. for (var t in ActionManager.Triggers) {
  44737. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44738. var t_int = parseInt(t);
  44739. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44740. return true;
  44741. }
  44742. }
  44743. }
  44744. return false;
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. /**
  44750. * Does exist one action manager that handles actions of a given trigger
  44751. * @param {number} trigger - the trigger to be tested
  44752. * @return {boolean} whether the trigger is handeled by at least one action manager
  44753. **/
  44754. ActionManager.HasSpecificTrigger = function (trigger) {
  44755. for (var t in ActionManager.Triggers) {
  44756. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44757. var t_int = parseInt(t);
  44758. if (t_int === trigger) {
  44759. return true;
  44760. }
  44761. }
  44762. }
  44763. return false;
  44764. };
  44765. /**
  44766. * Registers an action to this action manager
  44767. * @param {BABYLON.Action} action - the action to be registered
  44768. * @return {BABYLON.Action} the action amended (prepared) after registration
  44769. */
  44770. ActionManager.prototype.registerAction = function (action) {
  44771. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44772. if (this.getScene().actionManager !== this) {
  44773. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44774. return null;
  44775. }
  44776. }
  44777. this.actions.push(action);
  44778. if (ActionManager.Triggers[action.trigger]) {
  44779. ActionManager.Triggers[action.trigger]++;
  44780. }
  44781. else {
  44782. ActionManager.Triggers[action.trigger] = 1;
  44783. }
  44784. action._actionManager = this;
  44785. action._prepare();
  44786. return action;
  44787. };
  44788. /**
  44789. * Unregisters an action to this action manager
  44790. * @param action The action to be unregistered
  44791. * @return whether the action has been unregistered
  44792. */
  44793. ActionManager.prototype.unregisterAction = function (action) {
  44794. var index = this.actions.indexOf(action);
  44795. if (index !== -1) {
  44796. this.actions.splice(index, 1);
  44797. ActionManager.Triggers[action.trigger] -= 1;
  44798. if (ActionManager.Triggers[action.trigger] === 0) {
  44799. delete ActionManager.Triggers[action.trigger];
  44800. }
  44801. delete action._actionManager;
  44802. return true;
  44803. }
  44804. return false;
  44805. };
  44806. /**
  44807. * Process a specific trigger
  44808. * @param {number} trigger - the trigger to process
  44809. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44810. */
  44811. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44812. for (var index = 0; index < this.actions.length; index++) {
  44813. var action = this.actions[index];
  44814. if (action.trigger === trigger) {
  44815. if (evt) {
  44816. if (trigger === ActionManager.OnKeyUpTrigger
  44817. || trigger === ActionManager.OnKeyDownTrigger) {
  44818. var parameter = action.getTriggerParameter();
  44819. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44820. if (!parameter.toLowerCase) {
  44821. continue;
  44822. }
  44823. var lowerCase = parameter.toLowerCase();
  44824. if (lowerCase !== evt.sourceEvent.key) {
  44825. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44826. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44827. if (actualkey !== lowerCase) {
  44828. continue;
  44829. }
  44830. }
  44831. }
  44832. }
  44833. }
  44834. action._executeCurrent(evt);
  44835. }
  44836. }
  44837. };
  44838. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44839. var properties = propertyPath.split(".");
  44840. for (var index = 0; index < properties.length - 1; index++) {
  44841. target = target[properties[index]];
  44842. }
  44843. return target;
  44844. };
  44845. ActionManager.prototype._getProperty = function (propertyPath) {
  44846. var properties = propertyPath.split(".");
  44847. return properties[properties.length - 1];
  44848. };
  44849. ActionManager.prototype.serialize = function (name) {
  44850. var root = {
  44851. children: new Array(),
  44852. name: name,
  44853. type: 3,
  44854. properties: new Array() // Empty for root but required
  44855. };
  44856. for (var i = 0; i < this.actions.length; i++) {
  44857. var triggerObject = {
  44858. type: 0,
  44859. children: new Array(),
  44860. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44861. properties: new Array()
  44862. };
  44863. var triggerOptions = this.actions[i].triggerOptions;
  44864. if (triggerOptions && typeof triggerOptions !== "number") {
  44865. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44866. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44867. }
  44868. else {
  44869. var parameter = {};
  44870. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44871. if (triggerOptions.parameter.mesh) {
  44872. parameter._meshId = triggerOptions.parameter.mesh.id;
  44873. }
  44874. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44875. }
  44876. }
  44877. // Serialize child action, recursively
  44878. this.actions[i].serialize(triggerObject);
  44879. // Add serialized trigger
  44880. root.children.push(triggerObject);
  44881. }
  44882. return root;
  44883. };
  44884. ActionManager.Parse = function (parsedActions, object, scene) {
  44885. var actionManager = new ActionManager(scene);
  44886. if (object === null)
  44887. scene.actionManager = actionManager;
  44888. else
  44889. object.actionManager = actionManager;
  44890. // instanciate a new object
  44891. var instanciate = function (name, params) {
  44892. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44893. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44894. newInstance.constructor.apply(newInstance, params);
  44895. return newInstance;
  44896. };
  44897. var parseParameter = function (name, value, target, propertyPath) {
  44898. if (propertyPath === null) {
  44899. // String, boolean or float
  44900. var floatValue = parseFloat(value);
  44901. if (value === "true" || value === "false")
  44902. return value === "true";
  44903. else
  44904. return isNaN(floatValue) ? value : floatValue;
  44905. }
  44906. var effectiveTarget = propertyPath.split(".");
  44907. var values = value.split(",");
  44908. // Get effective Target
  44909. for (var i = 0; i < effectiveTarget.length; i++) {
  44910. target = target[effectiveTarget[i]];
  44911. }
  44912. // Return appropriate value with its type
  44913. if (typeof (target) === "boolean")
  44914. return values[0] === "true";
  44915. if (typeof (target) === "string")
  44916. return values[0];
  44917. // Parameters with multiple values such as Vector3 etc.
  44918. var split = new Array();
  44919. for (var i = 0; i < values.length; i++)
  44920. split.push(parseFloat(values[i]));
  44921. if (target instanceof BABYLON.Vector3)
  44922. return BABYLON.Vector3.FromArray(split);
  44923. if (target instanceof BABYLON.Vector4)
  44924. return BABYLON.Vector4.FromArray(split);
  44925. if (target instanceof BABYLON.Color3)
  44926. return BABYLON.Color3.FromArray(split);
  44927. if (target instanceof BABYLON.Color4)
  44928. return BABYLON.Color4.FromArray(split);
  44929. return parseFloat(values[0]);
  44930. };
  44931. // traverse graph per trigger
  44932. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44933. if (combineArray === void 0) { combineArray = null; }
  44934. if (parsedAction.detached)
  44935. return;
  44936. var parameters = new Array();
  44937. var target = null;
  44938. var propertyPath = null;
  44939. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44940. // Parameters
  44941. if (parsedAction.type === 2)
  44942. parameters.push(actionManager);
  44943. else
  44944. parameters.push(trigger);
  44945. if (combine) {
  44946. var actions = new Array();
  44947. for (var j = 0; j < parsedAction.combine.length; j++) {
  44948. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44949. }
  44950. parameters.push(actions);
  44951. }
  44952. else {
  44953. for (var i = 0; i < parsedAction.properties.length; i++) {
  44954. var value = parsedAction.properties[i].value;
  44955. var name = parsedAction.properties[i].name;
  44956. var targetType = parsedAction.properties[i].targetType;
  44957. if (name === "target")
  44958. if (targetType !== null && targetType === "SceneProperties")
  44959. value = target = scene;
  44960. else
  44961. value = target = scene.getNodeByName(value);
  44962. else if (name === "parent")
  44963. value = scene.getNodeByName(value);
  44964. else if (name === "sound")
  44965. value = scene.getSoundByName(value);
  44966. else if (name !== "propertyPath") {
  44967. if (parsedAction.type === 2 && name === "operator")
  44968. value = BABYLON.ValueCondition[value];
  44969. else
  44970. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44971. }
  44972. else {
  44973. propertyPath = value;
  44974. }
  44975. parameters.push(value);
  44976. }
  44977. }
  44978. if (combineArray === null) {
  44979. parameters.push(condition);
  44980. }
  44981. else {
  44982. parameters.push(null);
  44983. }
  44984. // If interpolate value action
  44985. if (parsedAction.name === "InterpolateValueAction") {
  44986. var param = parameters[parameters.length - 2];
  44987. parameters[parameters.length - 1] = param;
  44988. parameters[parameters.length - 2] = condition;
  44989. }
  44990. // Action or condition(s) and not CombineAction
  44991. var newAction = instanciate(parsedAction.name, parameters);
  44992. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44993. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44994. if (action)
  44995. action.then(nothing);
  44996. else
  44997. actionManager.registerAction(nothing);
  44998. action = nothing;
  44999. }
  45000. if (combineArray === null) {
  45001. if (newAction instanceof BABYLON.Condition) {
  45002. condition = newAction;
  45003. newAction = action;
  45004. }
  45005. else {
  45006. condition = null;
  45007. if (action)
  45008. action.then(newAction);
  45009. else
  45010. actionManager.registerAction(newAction);
  45011. }
  45012. }
  45013. else {
  45014. combineArray.push(newAction);
  45015. }
  45016. for (var i = 0; i < parsedAction.children.length; i++)
  45017. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45018. };
  45019. // triggers
  45020. for (var i = 0; i < parsedActions.children.length; i++) {
  45021. var triggerParams;
  45022. var trigger = parsedActions.children[i];
  45023. if (trigger.properties.length > 0) {
  45024. var param = trigger.properties[0].value;
  45025. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45026. if (value._meshId) {
  45027. value.mesh = scene.getMeshByID(value._meshId);
  45028. }
  45029. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45030. }
  45031. else
  45032. triggerParams = ActionManager[trigger.name];
  45033. for (var j = 0; j < trigger.children.length; j++) {
  45034. if (!trigger.detached)
  45035. traverse(trigger.children[j], triggerParams, null, null);
  45036. }
  45037. }
  45038. };
  45039. ActionManager.GetTriggerName = function (trigger) {
  45040. switch (trigger) {
  45041. case 0: return "NothingTrigger";
  45042. case 1: return "OnPickTrigger";
  45043. case 2: return "OnLeftPickTrigger";
  45044. case 3: return "OnRightPickTrigger";
  45045. case 4: return "OnCenterPickTrigger";
  45046. case 5: return "OnPickDownTrigger";
  45047. case 6: return "OnPickUpTrigger";
  45048. case 7: return "OnLongPressTrigger";
  45049. case 8: return "OnPointerOverTrigger";
  45050. case 9: return "OnPointerOutTrigger";
  45051. case 10: return "OnEveryFrameTrigger";
  45052. case 11: return "OnIntersectionEnterTrigger";
  45053. case 12: return "OnIntersectionExitTrigger";
  45054. case 13: return "OnKeyDownTrigger";
  45055. case 14: return "OnKeyUpTrigger";
  45056. case 15: return "OnPickOutTrigger";
  45057. default: return "";
  45058. }
  45059. };
  45060. // Statics
  45061. ActionManager._NothingTrigger = 0;
  45062. ActionManager._OnPickTrigger = 1;
  45063. ActionManager._OnLeftPickTrigger = 2;
  45064. ActionManager._OnRightPickTrigger = 3;
  45065. ActionManager._OnCenterPickTrigger = 4;
  45066. ActionManager._OnPickDownTrigger = 5;
  45067. ActionManager._OnDoublePickTrigger = 6;
  45068. ActionManager._OnPickUpTrigger = 7;
  45069. ActionManager._OnLongPressTrigger = 8;
  45070. ActionManager._OnPointerOverTrigger = 9;
  45071. ActionManager._OnPointerOutTrigger = 10;
  45072. ActionManager._OnEveryFrameTrigger = 11;
  45073. ActionManager._OnIntersectionEnterTrigger = 12;
  45074. ActionManager._OnIntersectionExitTrigger = 13;
  45075. ActionManager._OnKeyDownTrigger = 14;
  45076. ActionManager._OnKeyUpTrigger = 15;
  45077. ActionManager._OnPickOutTrigger = 16;
  45078. ActionManager.Triggers = {};
  45079. return ActionManager;
  45080. }());
  45081. BABYLON.ActionManager = ActionManager;
  45082. })(BABYLON || (BABYLON = {}));
  45083. //# sourceMappingURL=babylon.actionManager.js.map
  45084. var BABYLON;
  45085. (function (BABYLON) {
  45086. var InterpolateValueAction = /** @class */ (function (_super) {
  45087. __extends(InterpolateValueAction, _super);
  45088. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45089. if (duration === void 0) { duration = 1000; }
  45090. var _this = _super.call(this, triggerOptions, condition) || this;
  45091. _this.propertyPath = propertyPath;
  45092. _this.value = value;
  45093. _this.duration = duration;
  45094. _this.stopOtherAnimations = stopOtherAnimations;
  45095. _this.onInterpolationDone = onInterpolationDone;
  45096. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45097. _this._target = _this._effectiveTarget = target;
  45098. return _this;
  45099. }
  45100. InterpolateValueAction.prototype._prepare = function () {
  45101. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45102. this._property = this._getProperty(this.propertyPath);
  45103. };
  45104. InterpolateValueAction.prototype.execute = function () {
  45105. var _this = this;
  45106. var scene = this._actionManager.getScene();
  45107. var keys = [
  45108. {
  45109. frame: 0,
  45110. value: this._effectiveTarget[this._property]
  45111. }, {
  45112. frame: 100,
  45113. value: this.value
  45114. }
  45115. ];
  45116. var dataType;
  45117. if (typeof this.value === "number") {
  45118. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45119. }
  45120. else if (this.value instanceof BABYLON.Color3) {
  45121. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45122. }
  45123. else if (this.value instanceof BABYLON.Vector3) {
  45124. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45125. }
  45126. else if (this.value instanceof BABYLON.Matrix) {
  45127. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45128. }
  45129. else if (this.value instanceof BABYLON.Quaternion) {
  45130. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45131. }
  45132. else {
  45133. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45134. return;
  45135. }
  45136. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45137. animation.setKeys(keys);
  45138. if (this.stopOtherAnimations) {
  45139. scene.stopAnimation(this._effectiveTarget);
  45140. }
  45141. var wrapper = function () {
  45142. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45143. if (_this.onInterpolationDone) {
  45144. _this.onInterpolationDone();
  45145. }
  45146. };
  45147. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45148. };
  45149. InterpolateValueAction.prototype.serialize = function (parent) {
  45150. return _super.prototype._serialize.call(this, {
  45151. name: "InterpolateValueAction",
  45152. properties: [
  45153. BABYLON.Action._GetTargetProperty(this._target),
  45154. { name: "propertyPath", value: this.propertyPath },
  45155. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45156. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45157. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45158. ]
  45159. }, parent);
  45160. };
  45161. return InterpolateValueAction;
  45162. }(BABYLON.Action));
  45163. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45164. })(BABYLON || (BABYLON = {}));
  45165. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45166. var BABYLON;
  45167. (function (BABYLON) {
  45168. var SwitchBooleanAction = /** @class */ (function (_super) {
  45169. __extends(SwitchBooleanAction, _super);
  45170. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45171. var _this = _super.call(this, triggerOptions, condition) || this;
  45172. _this.propertyPath = propertyPath;
  45173. _this._target = _this._effectiveTarget = target;
  45174. return _this;
  45175. }
  45176. SwitchBooleanAction.prototype._prepare = function () {
  45177. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45178. this._property = this._getProperty(this.propertyPath);
  45179. };
  45180. SwitchBooleanAction.prototype.execute = function () {
  45181. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45182. };
  45183. SwitchBooleanAction.prototype.serialize = function (parent) {
  45184. return _super.prototype._serialize.call(this, {
  45185. name: "SwitchBooleanAction",
  45186. properties: [
  45187. BABYLON.Action._GetTargetProperty(this._target),
  45188. { name: "propertyPath", value: this.propertyPath }
  45189. ]
  45190. }, parent);
  45191. };
  45192. return SwitchBooleanAction;
  45193. }(BABYLON.Action));
  45194. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45195. var SetStateAction = /** @class */ (function (_super) {
  45196. __extends(SetStateAction, _super);
  45197. function SetStateAction(triggerOptions, target, value, condition) {
  45198. var _this = _super.call(this, triggerOptions, condition) || this;
  45199. _this.value = value;
  45200. _this._target = target;
  45201. return _this;
  45202. }
  45203. SetStateAction.prototype.execute = function () {
  45204. this._target.state = this.value;
  45205. };
  45206. SetStateAction.prototype.serialize = function (parent) {
  45207. return _super.prototype._serialize.call(this, {
  45208. name: "SetStateAction",
  45209. properties: [
  45210. BABYLON.Action._GetTargetProperty(this._target),
  45211. { name: "value", value: this.value }
  45212. ]
  45213. }, parent);
  45214. };
  45215. return SetStateAction;
  45216. }(BABYLON.Action));
  45217. BABYLON.SetStateAction = SetStateAction;
  45218. var SetValueAction = /** @class */ (function (_super) {
  45219. __extends(SetValueAction, _super);
  45220. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45221. var _this = _super.call(this, triggerOptions, condition) || this;
  45222. _this.propertyPath = propertyPath;
  45223. _this.value = value;
  45224. _this._target = _this._effectiveTarget = target;
  45225. return _this;
  45226. }
  45227. SetValueAction.prototype._prepare = function () {
  45228. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45229. this._property = this._getProperty(this.propertyPath);
  45230. };
  45231. SetValueAction.prototype.execute = function () {
  45232. this._effectiveTarget[this._property] = this.value;
  45233. if (this._target.markAsDirty) {
  45234. this._target.markAsDirty(this._property);
  45235. }
  45236. };
  45237. SetValueAction.prototype.serialize = function (parent) {
  45238. return _super.prototype._serialize.call(this, {
  45239. name: "SetValueAction",
  45240. properties: [
  45241. BABYLON.Action._GetTargetProperty(this._target),
  45242. { name: "propertyPath", value: this.propertyPath },
  45243. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45244. ]
  45245. }, parent);
  45246. };
  45247. return SetValueAction;
  45248. }(BABYLON.Action));
  45249. BABYLON.SetValueAction = SetValueAction;
  45250. var IncrementValueAction = /** @class */ (function (_super) {
  45251. __extends(IncrementValueAction, _super);
  45252. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45253. var _this = _super.call(this, triggerOptions, condition) || this;
  45254. _this.propertyPath = propertyPath;
  45255. _this.value = value;
  45256. _this._target = _this._effectiveTarget = target;
  45257. return _this;
  45258. }
  45259. IncrementValueAction.prototype._prepare = function () {
  45260. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45261. this._property = this._getProperty(this.propertyPath);
  45262. if (typeof this._effectiveTarget[this._property] !== "number") {
  45263. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45264. }
  45265. };
  45266. IncrementValueAction.prototype.execute = function () {
  45267. this._effectiveTarget[this._property] += this.value;
  45268. if (this._target.markAsDirty) {
  45269. this._target.markAsDirty(this._property);
  45270. }
  45271. };
  45272. IncrementValueAction.prototype.serialize = function (parent) {
  45273. return _super.prototype._serialize.call(this, {
  45274. name: "IncrementValueAction",
  45275. properties: [
  45276. BABYLON.Action._GetTargetProperty(this._target),
  45277. { name: "propertyPath", value: this.propertyPath },
  45278. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45279. ]
  45280. }, parent);
  45281. };
  45282. return IncrementValueAction;
  45283. }(BABYLON.Action));
  45284. BABYLON.IncrementValueAction = IncrementValueAction;
  45285. var PlayAnimationAction = /** @class */ (function (_super) {
  45286. __extends(PlayAnimationAction, _super);
  45287. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45288. var _this = _super.call(this, triggerOptions, condition) || this;
  45289. _this.from = from;
  45290. _this.to = to;
  45291. _this.loop = loop;
  45292. _this._target = target;
  45293. return _this;
  45294. }
  45295. PlayAnimationAction.prototype._prepare = function () {
  45296. };
  45297. PlayAnimationAction.prototype.execute = function () {
  45298. var scene = this._actionManager.getScene();
  45299. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45300. };
  45301. PlayAnimationAction.prototype.serialize = function (parent) {
  45302. return _super.prototype._serialize.call(this, {
  45303. name: "PlayAnimationAction",
  45304. properties: [
  45305. BABYLON.Action._GetTargetProperty(this._target),
  45306. { name: "from", value: String(this.from) },
  45307. { name: "to", value: String(this.to) },
  45308. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45309. ]
  45310. }, parent);
  45311. };
  45312. return PlayAnimationAction;
  45313. }(BABYLON.Action));
  45314. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45315. var StopAnimationAction = /** @class */ (function (_super) {
  45316. __extends(StopAnimationAction, _super);
  45317. function StopAnimationAction(triggerOptions, target, condition) {
  45318. var _this = _super.call(this, triggerOptions, condition) || this;
  45319. _this._target = target;
  45320. return _this;
  45321. }
  45322. StopAnimationAction.prototype._prepare = function () {
  45323. };
  45324. StopAnimationAction.prototype.execute = function () {
  45325. var scene = this._actionManager.getScene();
  45326. scene.stopAnimation(this._target);
  45327. };
  45328. StopAnimationAction.prototype.serialize = function (parent) {
  45329. return _super.prototype._serialize.call(this, {
  45330. name: "StopAnimationAction",
  45331. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45332. }, parent);
  45333. };
  45334. return StopAnimationAction;
  45335. }(BABYLON.Action));
  45336. BABYLON.StopAnimationAction = StopAnimationAction;
  45337. var DoNothingAction = /** @class */ (function (_super) {
  45338. __extends(DoNothingAction, _super);
  45339. function DoNothingAction(triggerOptions, condition) {
  45340. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45341. return _super.call(this, triggerOptions, condition) || this;
  45342. }
  45343. DoNothingAction.prototype.execute = function () {
  45344. };
  45345. DoNothingAction.prototype.serialize = function (parent) {
  45346. return _super.prototype._serialize.call(this, {
  45347. name: "DoNothingAction",
  45348. properties: []
  45349. }, parent);
  45350. };
  45351. return DoNothingAction;
  45352. }(BABYLON.Action));
  45353. BABYLON.DoNothingAction = DoNothingAction;
  45354. var CombineAction = /** @class */ (function (_super) {
  45355. __extends(CombineAction, _super);
  45356. function CombineAction(triggerOptions, children, condition) {
  45357. var _this = _super.call(this, triggerOptions, condition) || this;
  45358. _this.children = children;
  45359. return _this;
  45360. }
  45361. CombineAction.prototype._prepare = function () {
  45362. for (var index = 0; index < this.children.length; index++) {
  45363. this.children[index]._actionManager = this._actionManager;
  45364. this.children[index]._prepare();
  45365. }
  45366. };
  45367. CombineAction.prototype.execute = function (evt) {
  45368. for (var index = 0; index < this.children.length; index++) {
  45369. this.children[index].execute(evt);
  45370. }
  45371. };
  45372. CombineAction.prototype.serialize = function (parent) {
  45373. var serializationObject = _super.prototype._serialize.call(this, {
  45374. name: "CombineAction",
  45375. properties: [],
  45376. combine: []
  45377. }, parent);
  45378. for (var i = 0; i < this.children.length; i++) {
  45379. serializationObject.combine.push(this.children[i].serialize(null));
  45380. }
  45381. return serializationObject;
  45382. };
  45383. return CombineAction;
  45384. }(BABYLON.Action));
  45385. BABYLON.CombineAction = CombineAction;
  45386. var ExecuteCodeAction = /** @class */ (function (_super) {
  45387. __extends(ExecuteCodeAction, _super);
  45388. function ExecuteCodeAction(triggerOptions, func, condition) {
  45389. var _this = _super.call(this, triggerOptions, condition) || this;
  45390. _this.func = func;
  45391. return _this;
  45392. }
  45393. ExecuteCodeAction.prototype.execute = function (evt) {
  45394. this.func(evt);
  45395. };
  45396. return ExecuteCodeAction;
  45397. }(BABYLON.Action));
  45398. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45399. var SetParentAction = /** @class */ (function (_super) {
  45400. __extends(SetParentAction, _super);
  45401. function SetParentAction(triggerOptions, target, parent, condition) {
  45402. var _this = _super.call(this, triggerOptions, condition) || this;
  45403. _this._target = target;
  45404. _this._parent = parent;
  45405. return _this;
  45406. }
  45407. SetParentAction.prototype._prepare = function () {
  45408. };
  45409. SetParentAction.prototype.execute = function () {
  45410. if (this._target.parent === this._parent) {
  45411. return;
  45412. }
  45413. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45414. invertParentWorldMatrix.invert();
  45415. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45416. this._target.parent = this._parent;
  45417. };
  45418. SetParentAction.prototype.serialize = function (parent) {
  45419. return _super.prototype._serialize.call(this, {
  45420. name: "SetParentAction",
  45421. properties: [
  45422. BABYLON.Action._GetTargetProperty(this._target),
  45423. BABYLON.Action._GetTargetProperty(this._parent),
  45424. ]
  45425. }, parent);
  45426. };
  45427. return SetParentAction;
  45428. }(BABYLON.Action));
  45429. BABYLON.SetParentAction = SetParentAction;
  45430. var PlaySoundAction = /** @class */ (function (_super) {
  45431. __extends(PlaySoundAction, _super);
  45432. function PlaySoundAction(triggerOptions, sound, condition) {
  45433. var _this = _super.call(this, triggerOptions, condition) || this;
  45434. _this._sound = sound;
  45435. return _this;
  45436. }
  45437. PlaySoundAction.prototype._prepare = function () {
  45438. };
  45439. PlaySoundAction.prototype.execute = function () {
  45440. if (this._sound !== undefined)
  45441. this._sound.play();
  45442. };
  45443. PlaySoundAction.prototype.serialize = function (parent) {
  45444. return _super.prototype._serialize.call(this, {
  45445. name: "PlaySoundAction",
  45446. properties: [{ name: "sound", value: this._sound.name }]
  45447. }, parent);
  45448. };
  45449. return PlaySoundAction;
  45450. }(BABYLON.Action));
  45451. BABYLON.PlaySoundAction = PlaySoundAction;
  45452. var StopSoundAction = /** @class */ (function (_super) {
  45453. __extends(StopSoundAction, _super);
  45454. function StopSoundAction(triggerOptions, sound, condition) {
  45455. var _this = _super.call(this, triggerOptions, condition) || this;
  45456. _this._sound = sound;
  45457. return _this;
  45458. }
  45459. StopSoundAction.prototype._prepare = function () {
  45460. };
  45461. StopSoundAction.prototype.execute = function () {
  45462. if (this._sound !== undefined)
  45463. this._sound.stop();
  45464. };
  45465. StopSoundAction.prototype.serialize = function (parent) {
  45466. return _super.prototype._serialize.call(this, {
  45467. name: "StopSoundAction",
  45468. properties: [{ name: "sound", value: this._sound.name }]
  45469. }, parent);
  45470. };
  45471. return StopSoundAction;
  45472. }(BABYLON.Action));
  45473. BABYLON.StopSoundAction = StopSoundAction;
  45474. })(BABYLON || (BABYLON = {}));
  45475. //# sourceMappingURL=babylon.directActions.js.map
  45476. var BABYLON;
  45477. (function (BABYLON) {
  45478. var SpriteManager = /** @class */ (function () {
  45479. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45480. if (epsilon === void 0) { epsilon = 0.01; }
  45481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45482. this.name = name;
  45483. this.sprites = new Array();
  45484. this.renderingGroupId = 0;
  45485. this.layerMask = 0x0FFFFFFF;
  45486. this.fogEnabled = true;
  45487. this.isPickable = false;
  45488. /**
  45489. * An event triggered when the manager is disposed.
  45490. * @type {BABYLON.Observable}
  45491. */
  45492. this.onDisposeObservable = new BABYLON.Observable();
  45493. this._vertexBuffers = {};
  45494. this._capacity = capacity;
  45495. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45496. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45497. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45498. if (cellSize.width && cellSize.height) {
  45499. this.cellWidth = cellSize.width;
  45500. this.cellHeight = cellSize.height;
  45501. }
  45502. else if (cellSize !== undefined) {
  45503. this.cellWidth = cellSize;
  45504. this.cellHeight = cellSize;
  45505. }
  45506. else {
  45507. return;
  45508. }
  45509. this._epsilon = epsilon;
  45510. this._scene = scene;
  45511. this._scene.spriteManagers.push(this);
  45512. var indices = [];
  45513. var index = 0;
  45514. for (var count = 0; count < capacity; count++) {
  45515. indices.push(index);
  45516. indices.push(index + 1);
  45517. indices.push(index + 2);
  45518. indices.push(index);
  45519. indices.push(index + 2);
  45520. indices.push(index + 3);
  45521. index += 4;
  45522. }
  45523. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  45524. // VBO
  45525. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  45526. this._vertexData = new Float32Array(capacity * 16 * 4);
  45527. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  45528. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  45529. var options = this._buffer.createVertexBuffer("options", 4, 4);
  45530. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  45531. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  45532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45533. this._vertexBuffers["options"] = options;
  45534. this._vertexBuffers["cellInfo"] = cellInfo;
  45535. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45536. // Effects
  45537. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  45538. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  45539. }
  45540. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  45541. set: function (callback) {
  45542. if (this._onDisposeObserver) {
  45543. this.onDisposeObservable.remove(this._onDisposeObserver);
  45544. }
  45545. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45546. },
  45547. enumerable: true,
  45548. configurable: true
  45549. });
  45550. Object.defineProperty(SpriteManager.prototype, "texture", {
  45551. get: function () {
  45552. return this._spriteTexture;
  45553. },
  45554. set: function (value) {
  45555. this._spriteTexture = value;
  45556. },
  45557. enumerable: true,
  45558. configurable: true
  45559. });
  45560. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  45561. var arrayOffset = index * 16;
  45562. if (offsetX === 0)
  45563. offsetX = this._epsilon;
  45564. else if (offsetX === 1)
  45565. offsetX = 1 - this._epsilon;
  45566. if (offsetY === 0)
  45567. offsetY = this._epsilon;
  45568. else if (offsetY === 1)
  45569. offsetY = 1 - this._epsilon;
  45570. this._vertexData[arrayOffset] = sprite.position.x;
  45571. this._vertexData[arrayOffset + 1] = sprite.position.y;
  45572. this._vertexData[arrayOffset + 2] = sprite.position.z;
  45573. this._vertexData[arrayOffset + 3] = sprite.angle;
  45574. this._vertexData[arrayOffset + 4] = sprite.width;
  45575. this._vertexData[arrayOffset + 5] = sprite.height;
  45576. this._vertexData[arrayOffset + 6] = offsetX;
  45577. this._vertexData[arrayOffset + 7] = offsetY;
  45578. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  45579. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  45580. var offset = (sprite.cellIndex / rowSize) >> 0;
  45581. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  45582. this._vertexData[arrayOffset + 11] = offset;
  45583. // Color
  45584. this._vertexData[arrayOffset + 12] = sprite.color.r;
  45585. this._vertexData[arrayOffset + 13] = sprite.color.g;
  45586. this._vertexData[arrayOffset + 14] = sprite.color.b;
  45587. this._vertexData[arrayOffset + 15] = sprite.color.a;
  45588. };
  45589. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  45590. var count = Math.min(this._capacity, this.sprites.length);
  45591. var min = BABYLON.Vector3.Zero();
  45592. var max = BABYLON.Vector3.Zero();
  45593. var distance = Number.MAX_VALUE;
  45594. var currentSprite = null;
  45595. var cameraSpacePosition = BABYLON.Vector3.Zero();
  45596. var cameraView = camera.getViewMatrix();
  45597. for (var index = 0; index < count; index++) {
  45598. var sprite = this.sprites[index];
  45599. if (!sprite) {
  45600. continue;
  45601. }
  45602. if (predicate) {
  45603. if (!predicate(sprite)) {
  45604. continue;
  45605. }
  45606. }
  45607. else if (!sprite.isPickable) {
  45608. continue;
  45609. }
  45610. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  45611. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  45612. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  45613. if (ray.intersectsBoxMinMax(min, max)) {
  45614. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  45615. if (distance > currentDistance) {
  45616. distance = currentDistance;
  45617. currentSprite = sprite;
  45618. if (fastCheck) {
  45619. break;
  45620. }
  45621. }
  45622. }
  45623. }
  45624. if (currentSprite) {
  45625. var result = new BABYLON.PickingInfo();
  45626. result.hit = true;
  45627. result.pickedSprite = currentSprite;
  45628. result.distance = distance;
  45629. return result;
  45630. }
  45631. return null;
  45632. };
  45633. SpriteManager.prototype.render = function () {
  45634. // Check
  45635. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  45636. return;
  45637. var engine = this._scene.getEngine();
  45638. var baseSize = this._spriteTexture.getBaseSize();
  45639. // Sprites
  45640. var deltaTime = engine.getDeltaTime();
  45641. var max = Math.min(this._capacity, this.sprites.length);
  45642. var rowSize = baseSize.width / this.cellWidth;
  45643. var offset = 0;
  45644. for (var index = 0; index < max; index++) {
  45645. var sprite = this.sprites[index];
  45646. if (!sprite) {
  45647. continue;
  45648. }
  45649. sprite._animate(deltaTime);
  45650. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  45651. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  45652. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  45653. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  45654. }
  45655. this._buffer.update(this._vertexData);
  45656. // Render
  45657. var effect = this._effectBase;
  45658. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45659. effect = this._effectFog;
  45660. }
  45661. engine.enableEffect(effect);
  45662. var viewMatrix = this._scene.getViewMatrix();
  45663. effect.setTexture("diffuseSampler", this._spriteTexture);
  45664. effect.setMatrix("view", viewMatrix);
  45665. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45666. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  45667. // Fog
  45668. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45669. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  45670. effect.setColor3("vFogColor", this._scene.fogColor);
  45671. }
  45672. // VBOs
  45673. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45674. // Draw order
  45675. engine.setDepthFunctionToLessOrEqual();
  45676. effect.setBool("alphaTest", true);
  45677. engine.setColorWrite(false);
  45678. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45679. engine.setColorWrite(true);
  45680. effect.setBool("alphaTest", false);
  45681. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45682. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45683. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45684. };
  45685. SpriteManager.prototype.dispose = function () {
  45686. if (this._buffer) {
  45687. this._buffer.dispose();
  45688. this._buffer = null;
  45689. }
  45690. if (this._indexBuffer) {
  45691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45692. this._indexBuffer = null;
  45693. }
  45694. if (this._spriteTexture) {
  45695. this._spriteTexture.dispose();
  45696. this._spriteTexture = null;
  45697. }
  45698. // Remove from scene
  45699. var index = this._scene.spriteManagers.indexOf(this);
  45700. this._scene.spriteManagers.splice(index, 1);
  45701. // Callback
  45702. this.onDisposeObservable.notifyObservers(this);
  45703. this.onDisposeObservable.clear();
  45704. };
  45705. return SpriteManager;
  45706. }());
  45707. BABYLON.SpriteManager = SpriteManager;
  45708. })(BABYLON || (BABYLON = {}));
  45709. //# sourceMappingURL=babylon.spriteManager.js.map
  45710. var BABYLON;
  45711. (function (BABYLON) {
  45712. var Sprite = /** @class */ (function () {
  45713. function Sprite(name, manager) {
  45714. this.name = name;
  45715. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45716. this.width = 1.0;
  45717. this.height = 1.0;
  45718. this.angle = 0;
  45719. this.cellIndex = 0;
  45720. this.invertU = 0;
  45721. this.invertV = 0;
  45722. this.animations = new Array();
  45723. this.isPickable = false;
  45724. this._animationStarted = false;
  45725. this._loopAnimation = false;
  45726. this._fromIndex = 0;
  45727. this._toIndex = 0;
  45728. this._delay = 0;
  45729. this._direction = 1;
  45730. this._time = 0;
  45731. this._manager = manager;
  45732. this._manager.sprites.push(this);
  45733. this.position = BABYLON.Vector3.Zero();
  45734. }
  45735. Object.defineProperty(Sprite.prototype, "size", {
  45736. get: function () {
  45737. return this.width;
  45738. },
  45739. set: function (value) {
  45740. this.width = value;
  45741. this.height = value;
  45742. },
  45743. enumerable: true,
  45744. configurable: true
  45745. });
  45746. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45747. this._fromIndex = from;
  45748. this._toIndex = to;
  45749. this._loopAnimation = loop;
  45750. this._delay = delay;
  45751. this._animationStarted = true;
  45752. this._direction = from < to ? 1 : -1;
  45753. this.cellIndex = from;
  45754. this._time = 0;
  45755. this._onAnimationEnd = onAnimationEnd;
  45756. };
  45757. Sprite.prototype.stopAnimation = function () {
  45758. this._animationStarted = false;
  45759. };
  45760. Sprite.prototype._animate = function (deltaTime) {
  45761. if (!this._animationStarted)
  45762. return;
  45763. this._time += deltaTime;
  45764. if (this._time > this._delay) {
  45765. this._time = this._time % this._delay;
  45766. this.cellIndex += this._direction;
  45767. if (this.cellIndex > this._toIndex) {
  45768. if (this._loopAnimation) {
  45769. this.cellIndex = this._fromIndex;
  45770. }
  45771. else {
  45772. this.cellIndex = this._toIndex;
  45773. this._animationStarted = false;
  45774. if (this._onAnimationEnd) {
  45775. this._onAnimationEnd();
  45776. }
  45777. if (this.disposeWhenFinishedAnimating) {
  45778. this.dispose();
  45779. }
  45780. }
  45781. }
  45782. }
  45783. };
  45784. Sprite.prototype.dispose = function () {
  45785. for (var i = 0; i < this._manager.sprites.length; i++) {
  45786. if (this._manager.sprites[i] == this) {
  45787. this._manager.sprites.splice(i, 1);
  45788. }
  45789. }
  45790. };
  45791. return Sprite;
  45792. }());
  45793. BABYLON.Sprite = Sprite;
  45794. })(BABYLON || (BABYLON = {}));
  45795. //# sourceMappingURL=babylon.sprite.js.map
  45796. var BABYLON;
  45797. (function (BABYLON) {
  45798. var IntersectionInfo = /** @class */ (function () {
  45799. function IntersectionInfo(bu, bv, distance) {
  45800. this.bu = bu;
  45801. this.bv = bv;
  45802. this.distance = distance;
  45803. this.faceId = 0;
  45804. this.subMeshId = 0;
  45805. }
  45806. return IntersectionInfo;
  45807. }());
  45808. BABYLON.IntersectionInfo = IntersectionInfo;
  45809. var PickingInfo = /** @class */ (function () {
  45810. function PickingInfo() {
  45811. this.hit = false;
  45812. this.distance = 0;
  45813. this.pickedPoint = null;
  45814. this.pickedMesh = null;
  45815. this.bu = 0;
  45816. this.bv = 0;
  45817. this.faceId = -1;
  45818. this.subMeshId = 0;
  45819. this.pickedSprite = null;
  45820. }
  45821. // Methods
  45822. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45823. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45824. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45825. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45826. return null;
  45827. }
  45828. var indices = this.pickedMesh.getIndices();
  45829. if (!indices) {
  45830. return null;
  45831. }
  45832. var result;
  45833. if (useVerticesNormals) {
  45834. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45835. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45836. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45837. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45838. normal0 = normal0.scale(this.bu);
  45839. normal1 = normal1.scale(this.bv);
  45840. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45841. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45842. }
  45843. else {
  45844. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45845. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45846. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45847. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45848. var p1p2 = vertex1.subtract(vertex2);
  45849. var p3p2 = vertex3.subtract(vertex2);
  45850. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45851. }
  45852. if (useWorldCoordinates) {
  45853. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45854. }
  45855. return BABYLON.Vector3.Normalize(result);
  45856. };
  45857. PickingInfo.prototype.getTextureCoordinates = function () {
  45858. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45859. return null;
  45860. }
  45861. var indices = this.pickedMesh.getIndices();
  45862. if (!indices) {
  45863. return null;
  45864. }
  45865. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45866. if (!uvs) {
  45867. return null;
  45868. }
  45869. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45870. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45871. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45872. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45873. uv1 = uv1.scale(this.bu);
  45874. uv2 = uv2.scale(this.bv);
  45875. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45876. };
  45877. return PickingInfo;
  45878. }());
  45879. BABYLON.PickingInfo = PickingInfo;
  45880. })(BABYLON || (BABYLON = {}));
  45881. //# sourceMappingURL=babylon.pickingInfo.js.map
  45882. var BABYLON;
  45883. (function (BABYLON) {
  45884. var Ray = /** @class */ (function () {
  45885. function Ray(origin, direction, length) {
  45886. if (length === void 0) { length = Number.MAX_VALUE; }
  45887. this.origin = origin;
  45888. this.direction = direction;
  45889. this.length = length;
  45890. }
  45891. // Methods
  45892. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45893. var d = 0.0;
  45894. var maxValue = Number.MAX_VALUE;
  45895. var inv;
  45896. var min;
  45897. var max;
  45898. var temp;
  45899. if (Math.abs(this.direction.x) < 0.0000001) {
  45900. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45901. return false;
  45902. }
  45903. }
  45904. else {
  45905. inv = 1.0 / this.direction.x;
  45906. min = (minimum.x - this.origin.x) * inv;
  45907. max = (maximum.x - this.origin.x) * inv;
  45908. if (max === -Infinity) {
  45909. max = Infinity;
  45910. }
  45911. if (min > max) {
  45912. temp = min;
  45913. min = max;
  45914. max = temp;
  45915. }
  45916. d = Math.max(min, d);
  45917. maxValue = Math.min(max, maxValue);
  45918. if (d > maxValue) {
  45919. return false;
  45920. }
  45921. }
  45922. if (Math.abs(this.direction.y) < 0.0000001) {
  45923. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45924. return false;
  45925. }
  45926. }
  45927. else {
  45928. inv = 1.0 / this.direction.y;
  45929. min = (minimum.y - this.origin.y) * inv;
  45930. max = (maximum.y - this.origin.y) * inv;
  45931. if (max === -Infinity) {
  45932. max = Infinity;
  45933. }
  45934. if (min > max) {
  45935. temp = min;
  45936. min = max;
  45937. max = temp;
  45938. }
  45939. d = Math.max(min, d);
  45940. maxValue = Math.min(max, maxValue);
  45941. if (d > maxValue) {
  45942. return false;
  45943. }
  45944. }
  45945. if (Math.abs(this.direction.z) < 0.0000001) {
  45946. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45947. return false;
  45948. }
  45949. }
  45950. else {
  45951. inv = 1.0 / this.direction.z;
  45952. min = (minimum.z - this.origin.z) * inv;
  45953. max = (maximum.z - this.origin.z) * inv;
  45954. if (max === -Infinity) {
  45955. max = Infinity;
  45956. }
  45957. if (min > max) {
  45958. temp = min;
  45959. min = max;
  45960. max = temp;
  45961. }
  45962. d = Math.max(min, d);
  45963. maxValue = Math.min(max, maxValue);
  45964. if (d > maxValue) {
  45965. return false;
  45966. }
  45967. }
  45968. return true;
  45969. };
  45970. Ray.prototype.intersectsBox = function (box) {
  45971. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45972. };
  45973. Ray.prototype.intersectsSphere = function (sphere) {
  45974. var x = sphere.center.x - this.origin.x;
  45975. var y = sphere.center.y - this.origin.y;
  45976. var z = sphere.center.z - this.origin.z;
  45977. var pyth = (x * x) + (y * y) + (z * z);
  45978. var rr = sphere.radius * sphere.radius;
  45979. if (pyth <= rr) {
  45980. return true;
  45981. }
  45982. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45983. if (dot < 0.0) {
  45984. return false;
  45985. }
  45986. var temp = pyth - (dot * dot);
  45987. return temp <= rr;
  45988. };
  45989. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45990. if (!this._edge1) {
  45991. this._edge1 = BABYLON.Vector3.Zero();
  45992. this._edge2 = BABYLON.Vector3.Zero();
  45993. this._pvec = BABYLON.Vector3.Zero();
  45994. this._tvec = BABYLON.Vector3.Zero();
  45995. this._qvec = BABYLON.Vector3.Zero();
  45996. }
  45997. vertex1.subtractToRef(vertex0, this._edge1);
  45998. vertex2.subtractToRef(vertex0, this._edge2);
  45999. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46000. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46001. if (det === 0) {
  46002. return null;
  46003. }
  46004. var invdet = 1 / det;
  46005. this.origin.subtractToRef(vertex0, this._tvec);
  46006. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46007. if (bu < 0 || bu > 1.0) {
  46008. return null;
  46009. }
  46010. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46011. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46012. if (bv < 0 || bu + bv > 1.0) {
  46013. return null;
  46014. }
  46015. //check if the distance is longer than the predefined length.
  46016. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46017. if (distance > this.length) {
  46018. return null;
  46019. }
  46020. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46021. };
  46022. Ray.prototype.intersectsPlane = function (plane) {
  46023. var distance;
  46024. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46025. if (Math.abs(result1) < 9.99999997475243E-07) {
  46026. return null;
  46027. }
  46028. else {
  46029. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46030. distance = (-plane.d - result2) / result1;
  46031. if (distance < 0.0) {
  46032. if (distance < -9.99999997475243E-07) {
  46033. return null;
  46034. }
  46035. else {
  46036. return 0;
  46037. }
  46038. }
  46039. return distance;
  46040. }
  46041. };
  46042. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46043. var tm = BABYLON.Tmp.Matrix[0];
  46044. mesh.getWorldMatrix().invertToRef(tm);
  46045. if (this._tmpRay) {
  46046. Ray.TransformToRef(this, tm, this._tmpRay);
  46047. }
  46048. else {
  46049. this._tmpRay = Ray.Transform(this, tm);
  46050. }
  46051. return mesh.intersects(this._tmpRay, fastCheck);
  46052. };
  46053. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46054. if (results) {
  46055. results.length = 0;
  46056. }
  46057. else {
  46058. results = [];
  46059. }
  46060. for (var i = 0; i < meshes.length; i++) {
  46061. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46062. if (pickInfo.hit) {
  46063. results.push(pickInfo);
  46064. }
  46065. }
  46066. results.sort(this._comparePickingInfo);
  46067. return results;
  46068. };
  46069. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46070. if (pickingInfoA.distance < pickingInfoB.distance) {
  46071. return -1;
  46072. }
  46073. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46074. return 1;
  46075. }
  46076. else {
  46077. return 0;
  46078. }
  46079. };
  46080. /**
  46081. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46082. * @param sega the first point of the segment to test the intersection against
  46083. * @param segb the second point of the segment to test the intersection against
  46084. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46085. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46086. */
  46087. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46088. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46089. var u = segb.subtract(sega);
  46090. var v = rsegb.subtract(this.origin);
  46091. var w = sega.subtract(this.origin);
  46092. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46093. var b = BABYLON.Vector3.Dot(u, v);
  46094. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46095. var d = BABYLON.Vector3.Dot(u, w);
  46096. var e = BABYLON.Vector3.Dot(v, w);
  46097. var D = a * c - b * b; // always >= 0
  46098. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46099. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46100. // compute the line parameters of the two closest points
  46101. if (D < Ray.smallnum) {
  46102. sN = 0.0; // force using point P0 on segment S1
  46103. sD = 1.0; // to prevent possible division by 0.0 later
  46104. tN = e;
  46105. tD = c;
  46106. }
  46107. else {
  46108. sN = (b * e - c * d);
  46109. tN = (a * e - b * d);
  46110. if (sN < 0.0) {
  46111. sN = 0.0;
  46112. tN = e;
  46113. tD = c;
  46114. }
  46115. else if (sN > sD) {
  46116. sN = sD;
  46117. tN = e + b;
  46118. tD = c;
  46119. }
  46120. }
  46121. if (tN < 0.0) {
  46122. tN = 0.0;
  46123. // recompute sc for this edge
  46124. if (-d < 0.0) {
  46125. sN = 0.0;
  46126. }
  46127. else if (-d > a)
  46128. sN = sD;
  46129. else {
  46130. sN = -d;
  46131. sD = a;
  46132. }
  46133. }
  46134. else if (tN > tD) {
  46135. tN = tD;
  46136. // recompute sc for this edge
  46137. if ((-d + b) < 0.0) {
  46138. sN = 0;
  46139. }
  46140. else if ((-d + b) > a) {
  46141. sN = sD;
  46142. }
  46143. else {
  46144. sN = (-d + b);
  46145. sD = a;
  46146. }
  46147. }
  46148. // finally do the division to get sc and tc
  46149. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46150. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46151. // get the difference of the two closest points
  46152. var qtc = v.multiplyByFloats(tc, tc, tc);
  46153. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46154. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46155. if (isIntersected) {
  46156. return qtc.length();
  46157. }
  46158. return -1;
  46159. };
  46160. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46161. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46162. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46163. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46164. this.direction.normalize();
  46165. return this;
  46166. };
  46167. // Statics
  46168. Ray.Zero = function () {
  46169. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46170. };
  46171. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46172. var result = Ray.Zero();
  46173. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46174. };
  46175. /**
  46176. * 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
  46177. * transformed to the given world matrix.
  46178. * @param origin The origin point
  46179. * @param end The end point
  46180. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46181. */
  46182. Ray.CreateNewFromTo = function (origin, end, world) {
  46183. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46184. var direction = end.subtract(origin);
  46185. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46186. direction.normalize();
  46187. return Ray.Transform(new Ray(origin, direction, length), world);
  46188. };
  46189. Ray.Transform = function (ray, matrix) {
  46190. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46191. Ray.TransformToRef(ray, matrix, result);
  46192. return result;
  46193. };
  46194. Ray.TransformToRef = function (ray, matrix, result) {
  46195. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46196. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46197. result.length = ray.length;
  46198. var dir = result.direction;
  46199. var len = dir.length();
  46200. if (!(len === 0 || len === 1)) {
  46201. var num = 1.0 / len;
  46202. dir.x *= num;
  46203. dir.y *= num;
  46204. dir.z *= num;
  46205. result.length *= len;
  46206. }
  46207. };
  46208. Ray.smallnum = 0.00000001;
  46209. Ray.rayl = 10e8;
  46210. return Ray;
  46211. }());
  46212. BABYLON.Ray = Ray;
  46213. })(BABYLON || (BABYLON = {}));
  46214. //# sourceMappingURL=babylon.ray.js.map
  46215. var BABYLON;
  46216. (function (BABYLON) {
  46217. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46218. if (boxMin.x > sphereCenter.x + sphereRadius)
  46219. return false;
  46220. if (sphereCenter.x - sphereRadius > boxMax.x)
  46221. return false;
  46222. if (boxMin.y > sphereCenter.y + sphereRadius)
  46223. return false;
  46224. if (sphereCenter.y - sphereRadius > boxMax.y)
  46225. return false;
  46226. if (boxMin.z > sphereCenter.z + sphereRadius)
  46227. return false;
  46228. if (sphereCenter.z - sphereRadius > boxMax.z)
  46229. return false;
  46230. return true;
  46231. };
  46232. var getLowestRoot = (function () {
  46233. var result = { root: 0, found: false };
  46234. return function (a, b, c, maxR) {
  46235. result.root = 0;
  46236. result.found = false;
  46237. var determinant = b * b - 4.0 * a * c;
  46238. if (determinant < 0)
  46239. return result;
  46240. var sqrtD = Math.sqrt(determinant);
  46241. var r1 = (-b - sqrtD) / (2.0 * a);
  46242. var r2 = (-b + sqrtD) / (2.0 * a);
  46243. if (r1 > r2) {
  46244. var temp = r2;
  46245. r2 = r1;
  46246. r1 = temp;
  46247. }
  46248. if (r1 > 0 && r1 < maxR) {
  46249. result.root = r1;
  46250. result.found = true;
  46251. return result;
  46252. }
  46253. if (r2 > 0 && r2 < maxR) {
  46254. result.root = r2;
  46255. result.found = true;
  46256. return result;
  46257. }
  46258. return result;
  46259. };
  46260. })();
  46261. var Collider = /** @class */ (function () {
  46262. function Collider() {
  46263. this._collisionPoint = BABYLON.Vector3.Zero();
  46264. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46265. this._tempVector = BABYLON.Vector3.Zero();
  46266. this._tempVector2 = BABYLON.Vector3.Zero();
  46267. this._tempVector3 = BABYLON.Vector3.Zero();
  46268. this._tempVector4 = BABYLON.Vector3.Zero();
  46269. this._edge = BABYLON.Vector3.Zero();
  46270. this._baseToVertex = BABYLON.Vector3.Zero();
  46271. this._destinationPoint = BABYLON.Vector3.Zero();
  46272. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46273. this._displacementVector = BABYLON.Vector3.Zero();
  46274. this._radius = BABYLON.Vector3.One();
  46275. this._retry = 0;
  46276. this._basePointWorld = BABYLON.Vector3.Zero();
  46277. this._velocityWorld = BABYLON.Vector3.Zero();
  46278. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46279. this._collisionMask = -1;
  46280. }
  46281. Object.defineProperty(Collider.prototype, "collisionMask", {
  46282. get: function () {
  46283. return this._collisionMask;
  46284. },
  46285. set: function (mask) {
  46286. this._collisionMask = !isNaN(mask) ? mask : -1;
  46287. },
  46288. enumerable: true,
  46289. configurable: true
  46290. });
  46291. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46292. /**
  46293. * Gets the plane normal used to compute the sliding response (in local space)
  46294. */
  46295. get: function () {
  46296. return this._slidePlaneNormal;
  46297. },
  46298. enumerable: true,
  46299. configurable: true
  46300. });
  46301. // Methods
  46302. Collider.prototype._initialize = function (source, dir, e) {
  46303. this._velocity = dir;
  46304. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46305. this._basePoint = source;
  46306. source.multiplyToRef(this._radius, this._basePointWorld);
  46307. dir.multiplyToRef(this._radius, this._velocityWorld);
  46308. this._velocityWorldLength = this._velocityWorld.length();
  46309. this._epsilon = e;
  46310. this.collisionFound = false;
  46311. };
  46312. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46313. pa.subtractToRef(point, this._tempVector);
  46314. pb.subtractToRef(point, this._tempVector2);
  46315. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46316. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46317. if (d < 0)
  46318. return false;
  46319. pc.subtractToRef(point, this._tempVector3);
  46320. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46321. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46322. if (d < 0)
  46323. return false;
  46324. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46325. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46326. return d >= 0;
  46327. };
  46328. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46329. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46330. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46331. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46332. return false;
  46333. }
  46334. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46335. return false;
  46336. return true;
  46337. };
  46338. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46339. var t0;
  46340. var embeddedInPlane = false;
  46341. //defensive programming, actually not needed.
  46342. if (!trianglePlaneArray) {
  46343. trianglePlaneArray = [];
  46344. }
  46345. if (!trianglePlaneArray[faceIndex]) {
  46346. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46347. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46348. }
  46349. var trianglePlane = trianglePlaneArray[faceIndex];
  46350. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46351. return;
  46352. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46353. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46354. if (normalDotVelocity == 0) {
  46355. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46356. return;
  46357. embeddedInPlane = true;
  46358. t0 = 0;
  46359. }
  46360. else {
  46361. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46362. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46363. if (t0 > t1) {
  46364. var temp = t1;
  46365. t1 = t0;
  46366. t0 = temp;
  46367. }
  46368. if (t0 > 1.0 || t1 < 0.0)
  46369. return;
  46370. if (t0 < 0)
  46371. t0 = 0;
  46372. if (t0 > 1.0)
  46373. t0 = 1.0;
  46374. }
  46375. this._collisionPoint.copyFromFloats(0, 0, 0);
  46376. var found = false;
  46377. var t = 1.0;
  46378. if (!embeddedInPlane) {
  46379. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46380. this._velocity.scaleToRef(t0, this._tempVector);
  46381. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46382. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46383. found = true;
  46384. t = t0;
  46385. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46386. }
  46387. }
  46388. if (!found) {
  46389. var velocitySquaredLength = this._velocity.lengthSquared();
  46390. var a = velocitySquaredLength;
  46391. this._basePoint.subtractToRef(p1, this._tempVector);
  46392. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46393. var c = this._tempVector.lengthSquared() - 1.0;
  46394. var lowestRoot = getLowestRoot(a, b, c, t);
  46395. if (lowestRoot.found) {
  46396. t = lowestRoot.root;
  46397. found = true;
  46398. this._collisionPoint.copyFrom(p1);
  46399. }
  46400. this._basePoint.subtractToRef(p2, this._tempVector);
  46401. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46402. c = this._tempVector.lengthSquared() - 1.0;
  46403. lowestRoot = getLowestRoot(a, b, c, t);
  46404. if (lowestRoot.found) {
  46405. t = lowestRoot.root;
  46406. found = true;
  46407. this._collisionPoint.copyFrom(p2);
  46408. }
  46409. this._basePoint.subtractToRef(p3, this._tempVector);
  46410. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46411. c = this._tempVector.lengthSquared() - 1.0;
  46412. lowestRoot = getLowestRoot(a, b, c, t);
  46413. if (lowestRoot.found) {
  46414. t = lowestRoot.root;
  46415. found = true;
  46416. this._collisionPoint.copyFrom(p3);
  46417. }
  46418. p2.subtractToRef(p1, this._edge);
  46419. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46420. var edgeSquaredLength = this._edge.lengthSquared();
  46421. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46422. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46423. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46424. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46425. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46426. lowestRoot = getLowestRoot(a, b, c, t);
  46427. if (lowestRoot.found) {
  46428. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46429. if (f >= 0.0 && f <= 1.0) {
  46430. t = lowestRoot.root;
  46431. found = true;
  46432. this._edge.scaleInPlace(f);
  46433. p1.addToRef(this._edge, this._collisionPoint);
  46434. }
  46435. }
  46436. p3.subtractToRef(p2, this._edge);
  46437. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46438. edgeSquaredLength = this._edge.lengthSquared();
  46439. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46440. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46441. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46442. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46443. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46444. lowestRoot = getLowestRoot(a, b, c, t);
  46445. if (lowestRoot.found) {
  46446. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46447. if (f >= 0.0 && f <= 1.0) {
  46448. t = lowestRoot.root;
  46449. found = true;
  46450. this._edge.scaleInPlace(f);
  46451. p2.addToRef(this._edge, this._collisionPoint);
  46452. }
  46453. }
  46454. p1.subtractToRef(p3, this._edge);
  46455. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46456. edgeSquaredLength = this._edge.lengthSquared();
  46457. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46458. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46459. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46460. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46461. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46462. lowestRoot = getLowestRoot(a, b, c, t);
  46463. if (lowestRoot.found) {
  46464. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46465. if (f >= 0.0 && f <= 1.0) {
  46466. t = lowestRoot.root;
  46467. found = true;
  46468. this._edge.scaleInPlace(f);
  46469. p3.addToRef(this._edge, this._collisionPoint);
  46470. }
  46471. }
  46472. }
  46473. if (found) {
  46474. var distToCollision = t * this._velocity.length();
  46475. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46476. if (!this.intersectionPoint) {
  46477. this.intersectionPoint = this._collisionPoint.clone();
  46478. }
  46479. else {
  46480. this.intersectionPoint.copyFrom(this._collisionPoint);
  46481. }
  46482. this._nearestDistance = distToCollision;
  46483. this.collisionFound = true;
  46484. }
  46485. }
  46486. };
  46487. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46488. for (var i = indexStart; i < indexEnd; i += 3) {
  46489. var p1 = pts[indices[i] - decal];
  46490. var p2 = pts[indices[i + 1] - decal];
  46491. var p3 = pts[indices[i + 2] - decal];
  46492. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46493. }
  46494. };
  46495. Collider.prototype._getResponse = function (pos, vel) {
  46496. pos.addToRef(vel, this._destinationPoint);
  46497. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46498. this._basePoint.addToRef(vel, pos);
  46499. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46500. this._slidePlaneNormal.normalize();
  46501. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46502. pos.addInPlace(this._displacementVector);
  46503. this.intersectionPoint.addInPlace(this._displacementVector);
  46504. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  46505. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  46506. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  46507. };
  46508. return Collider;
  46509. }());
  46510. BABYLON.Collider = Collider;
  46511. })(BABYLON || (BABYLON = {}));
  46512. //# sourceMappingURL=babylon.collider.js.map
  46513. var BABYLON;
  46514. (function (BABYLON) {
  46515. //WebWorker code will be inserted to this variable.
  46516. BABYLON.CollisionWorker = "";
  46517. var WorkerTaskType;
  46518. (function (WorkerTaskType) {
  46519. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  46520. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  46521. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  46522. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  46523. var WorkerReplyType;
  46524. (function (WorkerReplyType) {
  46525. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  46526. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  46527. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  46528. var CollisionCoordinatorWorker = /** @class */ (function () {
  46529. function CollisionCoordinatorWorker() {
  46530. var _this = this;
  46531. this._scaledPosition = BABYLON.Vector3.Zero();
  46532. this._scaledVelocity = BABYLON.Vector3.Zero();
  46533. this.onMeshUpdated = function (transformNode) {
  46534. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  46535. };
  46536. this.onGeometryUpdated = function (geometry) {
  46537. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  46538. };
  46539. this._afterRender = function () {
  46540. if (!_this._init)
  46541. return;
  46542. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  46543. return;
  46544. }
  46545. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  46546. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  46547. if (_this._runningUpdated > 4) {
  46548. return;
  46549. }
  46550. ++_this._runningUpdated;
  46551. var payload = {
  46552. updatedMeshes: _this._addUpdateMeshesList,
  46553. updatedGeometries: _this._addUpdateGeometriesList,
  46554. removedGeometries: _this._toRemoveGeometryArray,
  46555. removedMeshes: _this._toRemoveMeshesArray
  46556. };
  46557. var message = {
  46558. payload: payload,
  46559. taskType: WorkerTaskType.UPDATE
  46560. };
  46561. var serializable = [];
  46562. for (var id in payload.updatedGeometries) {
  46563. if (payload.updatedGeometries.hasOwnProperty(id)) {
  46564. //prepare transferables
  46565. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  46566. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  46567. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  46568. }
  46569. }
  46570. _this._worker.postMessage(message, serializable);
  46571. _this._addUpdateMeshesList = {};
  46572. _this._addUpdateGeometriesList = {};
  46573. _this._toRemoveGeometryArray = [];
  46574. _this._toRemoveMeshesArray = [];
  46575. };
  46576. this._onMessageFromWorker = function (e) {
  46577. var returnData = e.data;
  46578. if (returnData.error != WorkerReplyType.SUCCESS) {
  46579. //TODO what errors can be returned from the worker?
  46580. BABYLON.Tools.Warn("error returned from worker!");
  46581. return;
  46582. }
  46583. switch (returnData.taskType) {
  46584. case WorkerTaskType.INIT:
  46585. _this._init = true;
  46586. //Update the worked with ALL of the scene's current state
  46587. _this._scene.meshes.forEach(function (mesh) {
  46588. _this.onMeshAdded(mesh);
  46589. });
  46590. _this._scene.getGeometries().forEach(function (geometry) {
  46591. _this.onGeometryAdded(geometry);
  46592. });
  46593. break;
  46594. case WorkerTaskType.UPDATE:
  46595. _this._runningUpdated--;
  46596. break;
  46597. case WorkerTaskType.COLLIDE:
  46598. var returnPayload = returnData.payload;
  46599. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  46600. return;
  46601. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  46602. if (callback) {
  46603. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  46604. if (mesh) {
  46605. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  46606. }
  46607. }
  46608. //cleanup
  46609. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  46610. break;
  46611. }
  46612. };
  46613. this._collisionsCallbackArray = [];
  46614. this._init = false;
  46615. this._runningUpdated = 0;
  46616. this._addUpdateMeshesList = {};
  46617. this._addUpdateGeometriesList = {};
  46618. this._toRemoveGeometryArray = [];
  46619. this._toRemoveMeshesArray = [];
  46620. }
  46621. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46622. if (!this._init)
  46623. return;
  46624. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  46625. return;
  46626. position.divideToRef(collider._radius, this._scaledPosition);
  46627. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46628. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  46629. var payload = {
  46630. collider: {
  46631. position: this._scaledPosition.asArray(),
  46632. velocity: this._scaledVelocity.asArray(),
  46633. radius: collider._radius.asArray()
  46634. },
  46635. collisionId: collisionIndex,
  46636. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  46637. maximumRetry: maximumRetry
  46638. };
  46639. var message = {
  46640. payload: payload,
  46641. taskType: WorkerTaskType.COLLIDE
  46642. };
  46643. this._worker.postMessage(message);
  46644. };
  46645. CollisionCoordinatorWorker.prototype.init = function (scene) {
  46646. this._scene = scene;
  46647. this._scene.registerAfterRender(this._afterRender);
  46648. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  46649. this._worker = new Worker(workerUrl);
  46650. this._worker.onmessage = this._onMessageFromWorker;
  46651. var message = {
  46652. payload: {},
  46653. taskType: WorkerTaskType.INIT
  46654. };
  46655. this._worker.postMessage(message);
  46656. };
  46657. CollisionCoordinatorWorker.prototype.destroy = function () {
  46658. this._scene.unregisterAfterRender(this._afterRender);
  46659. this._worker.terminate();
  46660. };
  46661. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  46662. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  46663. this.onMeshUpdated(mesh);
  46664. };
  46665. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  46666. this._toRemoveMeshesArray.push(mesh.uniqueId);
  46667. };
  46668. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  46669. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  46670. geometry.onGeometryUpdated = this.onGeometryUpdated;
  46671. this.onGeometryUpdated(geometry);
  46672. };
  46673. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  46674. this._toRemoveGeometryArray.push(geometry.id);
  46675. };
  46676. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  46677. var submeshes = [];
  46678. if (mesh.subMeshes) {
  46679. submeshes = mesh.subMeshes.map(function (sm, idx) {
  46680. var boundingInfo = sm.getBoundingInfo();
  46681. return {
  46682. position: idx,
  46683. verticesStart: sm.verticesStart,
  46684. verticesCount: sm.verticesCount,
  46685. indexStart: sm.indexStart,
  46686. indexCount: sm.indexCount,
  46687. hasMaterial: !!sm.getMaterial(),
  46688. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46689. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46690. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46691. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  46692. };
  46693. });
  46694. }
  46695. var geometryId = null;
  46696. if (mesh instanceof BABYLON.Mesh) {
  46697. var geometry = mesh.geometry;
  46698. geometryId = geometry ? geometry.id : null;
  46699. }
  46700. else if (mesh instanceof BABYLON.InstancedMesh) {
  46701. var geometry = mesh.sourceMesh.geometry;
  46702. geometryId = geometry ? geometry.id : null;
  46703. }
  46704. var boundingInfo = mesh.getBoundingInfo();
  46705. return {
  46706. uniqueId: mesh.uniqueId,
  46707. id: mesh.id,
  46708. name: mesh.name,
  46709. geometryId: geometryId,
  46710. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46711. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46712. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46713. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  46714. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  46715. subMeshes: submeshes,
  46716. checkCollisions: mesh.checkCollisions
  46717. };
  46718. };
  46719. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  46720. return {
  46721. id: geometry.id,
  46722. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  46723. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  46724. indices: new Uint32Array(geometry.getIndices() || []),
  46725. };
  46726. };
  46727. return CollisionCoordinatorWorker;
  46728. }());
  46729. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  46730. var CollisionCoordinatorLegacy = /** @class */ (function () {
  46731. function CollisionCoordinatorLegacy() {
  46732. this._scaledPosition = BABYLON.Vector3.Zero();
  46733. this._scaledVelocity = BABYLON.Vector3.Zero();
  46734. this._finalPosition = BABYLON.Vector3.Zero();
  46735. }
  46736. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46737. position.divideToRef(collider._radius, this._scaledPosition);
  46738. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46739. collider.collidedMesh = null;
  46740. collider._retry = 0;
  46741. collider._initialVelocity = this._scaledVelocity;
  46742. collider._initialPosition = this._scaledPosition;
  46743. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46744. this._finalPosition.multiplyInPlace(collider._radius);
  46745. //run the callback
  46746. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46747. };
  46748. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46749. this._scene = scene;
  46750. };
  46751. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46752. //Legacy need no destruction method.
  46753. };
  46754. //No update in legacy mode
  46755. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46756. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46757. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46758. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46759. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46760. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46761. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46762. if (excludedMesh === void 0) { excludedMesh = null; }
  46763. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46764. if (collider._retry >= maximumRetry) {
  46765. finalPosition.copyFrom(position);
  46766. return;
  46767. }
  46768. // Check if this is a mesh else camera or -1
  46769. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46770. collider._initialize(position, velocity, closeDistance);
  46771. // Check all meshes
  46772. for (var index = 0; index < this._scene.meshes.length; index++) {
  46773. var mesh = this._scene.meshes[index];
  46774. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46775. mesh._checkCollision(collider);
  46776. }
  46777. }
  46778. if (!collider.collisionFound) {
  46779. position.addToRef(velocity, finalPosition);
  46780. return;
  46781. }
  46782. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46783. collider._getResponse(position, velocity);
  46784. }
  46785. if (velocity.length() <= closeDistance) {
  46786. finalPosition.copyFrom(position);
  46787. return;
  46788. }
  46789. collider._retry++;
  46790. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46791. };
  46792. return CollisionCoordinatorLegacy;
  46793. }());
  46794. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46795. })(BABYLON || (BABYLON = {}));
  46796. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46797. var BABYLON;
  46798. (function (BABYLON) {
  46799. /**
  46800. * A particle represents one of the element emitted by a particle system.
  46801. * This is mainly define by its coordinates, direction, velocity and age.
  46802. */
  46803. var Particle = /** @class */ (function () {
  46804. /**
  46805. * Creates a new instance of @see Particle
  46806. * @param particleSystem the particle system the particle belongs to
  46807. */
  46808. function Particle(particleSystem) {
  46809. this.particleSystem = particleSystem;
  46810. /**
  46811. * The world position of the particle in the scene.
  46812. */
  46813. this.position = BABYLON.Vector3.Zero();
  46814. /**
  46815. * The world direction of the particle in the scene.
  46816. */
  46817. this.direction = BABYLON.Vector3.Zero();
  46818. /**
  46819. * The color of the particle.
  46820. */
  46821. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46822. /**
  46823. * The color change of the particle per step.
  46824. */
  46825. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46826. /**
  46827. * Defines how long will the life of the particle be.
  46828. */
  46829. this.lifeTime = 1.0;
  46830. /**
  46831. * The current age of the particle.
  46832. */
  46833. this.age = 0;
  46834. /**
  46835. * The current size of the particle.
  46836. */
  46837. this.size = 0;
  46838. /**
  46839. * The current angle of the particle.
  46840. */
  46841. this.angle = 0;
  46842. /**
  46843. * Defines how fast is the angle changing.
  46844. */
  46845. this.angularSpeed = 0;
  46846. /**
  46847. * Defines the cell index used by the particle to be rendered from a sprite.
  46848. */
  46849. this.cellIndex = 0;
  46850. this._currentFrameCounter = 0;
  46851. if (!this.particleSystem.isAnimationSheetEnabled) {
  46852. return;
  46853. }
  46854. this.cellIndex = this.particleSystem.startSpriteCellID;
  46855. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46856. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46857. }
  46858. else {
  46859. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46860. }
  46861. }
  46862. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46863. // (ageOffset / scaledUpdateSpeed) / available cells
  46864. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46865. this._currentFrameCounter += scaledUpdateSpeed;
  46866. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46867. this._currentFrameCounter = 0;
  46868. this.cellIndex++;
  46869. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46870. this.cellIndex = this.particleSystem.endSpriteCellID;
  46871. }
  46872. }
  46873. };
  46874. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46875. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46876. this.cellIndex++;
  46877. this._currentFrameCounter = 0;
  46878. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46879. if (this.particleSystem.spriteCellLoop) {
  46880. this.cellIndex = this.particleSystem.startSpriteCellID;
  46881. }
  46882. else {
  46883. this.cellIndex = this.particleSystem.endSpriteCellID;
  46884. }
  46885. }
  46886. }
  46887. else {
  46888. this._currentFrameCounter++;
  46889. }
  46890. };
  46891. /**
  46892. * Copy the properties of particle to another one.
  46893. * @param other the particle to copy the information to.
  46894. */
  46895. Particle.prototype.copyTo = function (other) {
  46896. other.position.copyFrom(this.position);
  46897. other.direction.copyFrom(this.direction);
  46898. other.color.copyFrom(this.color);
  46899. other.colorStep.copyFrom(this.colorStep);
  46900. other.lifeTime = this.lifeTime;
  46901. other.age = this.age;
  46902. other.size = this.size;
  46903. other.angle = this.angle;
  46904. other.angularSpeed = this.angularSpeed;
  46905. other.particleSystem = this.particleSystem;
  46906. other.cellIndex = this.cellIndex;
  46907. };
  46908. return Particle;
  46909. }());
  46910. BABYLON.Particle = Particle;
  46911. })(BABYLON || (BABYLON = {}));
  46912. //# sourceMappingURL=babylon.particle.js.map
  46913. var BABYLON;
  46914. (function (BABYLON) {
  46915. /**
  46916. * This represents a particle system in Babylon.
  46917. * 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.
  46918. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  46919. * @example https://doc.babylonjs.com/babylon101/particles
  46920. */
  46921. var ParticleSystem = /** @class */ (function () {
  46922. /**
  46923. * Instantiates a particle system.
  46924. * 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.
  46925. * @param name The name of the particle system
  46926. * @param capacity The max number of particles alive at the same time
  46927. * @param scene The scene the particle system belongs to
  46928. * @param customEffect a custom effect used to change the way particles are rendered by default
  46929. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  46930. * @param epsilon Offset used to render the particles
  46931. */
  46932. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  46933. if (customEffect === void 0) { customEffect = null; }
  46934. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  46935. if (epsilon === void 0) { epsilon = 0.01; }
  46936. var _this = this;
  46937. /**
  46938. * List of animations used by the particle system.
  46939. */
  46940. this.animations = [];
  46941. /**
  46942. * The rendering group used by the Particle system to chose when to render.
  46943. */
  46944. this.renderingGroupId = 0;
  46945. /**
  46946. * The emitter represents the Mesh or position we are attaching the particle system to.
  46947. */
  46948. this.emitter = null;
  46949. /**
  46950. * The density of particles, the rate of particle flow
  46951. */
  46952. this.emitRate = 10;
  46953. /**
  46954. * If you want to launch only a few particles at once, that can be done, as well.
  46955. */
  46956. this.manualEmitCount = -1;
  46957. /**
  46958. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  46959. */
  46960. this.updateSpeed = 0.01;
  46961. /**
  46962. * The amount of time the particle system is running (depends of the overall speed above).
  46963. */
  46964. this.targetStopDuration = 0;
  46965. /**
  46966. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  46967. */
  46968. this.disposeOnStop = false;
  46969. /**
  46970. * Minimum power of emitting particles.
  46971. */
  46972. this.minEmitPower = 1;
  46973. /**
  46974. * Maximum power of emitting particles.
  46975. */
  46976. this.maxEmitPower = 1;
  46977. /**
  46978. * Minimum life time of emitting particles.
  46979. */
  46980. this.minLifeTime = 1;
  46981. /**
  46982. * Maximum life time of emitting particles.
  46983. */
  46984. this.maxLifeTime = 1;
  46985. /**
  46986. * Minimum Size of emitting particles.
  46987. */
  46988. this.minSize = 1;
  46989. /**
  46990. * Maximum Size of emitting particles.
  46991. */
  46992. this.maxSize = 1;
  46993. /**
  46994. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  46995. */
  46996. this.minAngularSpeed = 0;
  46997. /**
  46998. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  46999. */
  47000. this.maxAngularSpeed = 0;
  47001. /**
  47002. * The layer mask we are rendering the particles through.
  47003. */
  47004. this.layerMask = 0x0FFFFFFF;
  47005. /**
  47006. * This can help using your own shader to render the particle system.
  47007. * The according effect will be created
  47008. */
  47009. this.customShader = null;
  47010. /**
  47011. * By default particle system starts as soon as they are created. This prevents the
  47012. * automatic start to happen and let you decide when to start emitting particles.
  47013. */
  47014. this.preventAutoStart = false;
  47015. /**
  47016. * Callback triggered when the particle animation is ending.
  47017. */
  47018. this.onAnimationEnd = null;
  47019. /**
  47020. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47021. */
  47022. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47023. /**
  47024. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47025. * to override the particles.
  47026. */
  47027. this.forceDepthWrite = false;
  47028. /**
  47029. * You can use gravity if you want to give an orientation to your particles.
  47030. */
  47031. this.gravity = BABYLON.Vector3.Zero();
  47032. /**
  47033. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47034. */
  47035. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47036. /**
  47037. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47038. */
  47039. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47040. /**
  47041. * 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.
  47042. */
  47043. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47044. /**
  47045. * 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.
  47046. */
  47047. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47048. /**
  47049. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47050. */
  47051. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47052. /**
  47053. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47054. */
  47055. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47056. /**
  47057. * Color the particle will have at the end of its lifetime.
  47058. */
  47059. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47060. /**
  47061. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47062. */
  47063. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47064. /**
  47065. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47066. */
  47067. this.spriteCellLoop = true;
  47068. /**
  47069. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47070. */
  47071. this.spriteCellChangeSpeed = 0;
  47072. /**
  47073. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47074. */
  47075. this.startSpriteCellID = 0;
  47076. /**
  47077. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47078. */
  47079. this.endSpriteCellID = 0;
  47080. /**
  47081. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47082. */
  47083. this.spriteCellWidth = 0;
  47084. /**
  47085. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47086. */
  47087. this.spriteCellHeight = 0;
  47088. /**
  47089. * An event triggered when the system is disposed.
  47090. */
  47091. this.onDisposeObservable = new BABYLON.Observable();
  47092. this._particles = new Array();
  47093. this._stockParticles = new Array();
  47094. this._newPartsExcess = 0;
  47095. this._vertexBuffers = {};
  47096. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47097. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47098. this._scaledDirection = BABYLON.Vector3.Zero();
  47099. this._scaledGravity = BABYLON.Vector3.Zero();
  47100. this._currentRenderId = -1;
  47101. this._started = false;
  47102. this._stopped = false;
  47103. this._actualFrame = 0;
  47104. this._vertexBufferSize = 11;
  47105. this._appendParticleVertexes = null;
  47106. this.id = name;
  47107. this.name = name;
  47108. this._capacity = capacity;
  47109. this._epsilon = epsilon;
  47110. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47111. if (isAnimationSheetEnabled) {
  47112. this._vertexBufferSize = 12;
  47113. }
  47114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47115. this._customEffect = customEffect;
  47116. scene.particleSystems.push(this);
  47117. this._createIndexBuffer();
  47118. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47119. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47120. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47121. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47122. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47123. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47124. if (this._isAnimationSheetEnabled) {
  47125. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47126. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47127. }
  47128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47129. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47130. this._vertexBuffers["options"] = options;
  47131. // Default behaviors
  47132. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47133. this.updateFunction = function (particles) {
  47134. for (var index = 0; index < particles.length; index++) {
  47135. var particle = particles[index];
  47136. particle.age += _this._scaledUpdateSpeed;
  47137. if (particle.age >= particle.lifeTime) {
  47138. _this.recycleParticle(particle);
  47139. index--;
  47140. continue;
  47141. }
  47142. else {
  47143. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47144. particle.color.addInPlace(_this._scaledColorStep);
  47145. if (particle.color.a < 0)
  47146. particle.color.a = 0;
  47147. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47148. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47149. particle.position.addInPlace(_this._scaledDirection);
  47150. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47151. particle.direction.addInPlace(_this._scaledGravity);
  47152. if (_this._isAnimationSheetEnabled) {
  47153. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47154. }
  47155. }
  47156. }
  47157. };
  47158. }
  47159. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47160. /**
  47161. * Sets a callback that will be triggered when the system is disposed.
  47162. */
  47163. set: function (callback) {
  47164. if (this._onDisposeObserver) {
  47165. this.onDisposeObservable.remove(this._onDisposeObserver);
  47166. }
  47167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47168. },
  47169. enumerable: true,
  47170. configurable: true
  47171. });
  47172. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47173. /**
  47174. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47175. */
  47176. get: function () {
  47177. return this._isAnimationSheetEnabled;
  47178. },
  47179. enumerable: true,
  47180. configurable: true
  47181. });
  47182. ParticleSystem.prototype._createIndexBuffer = function () {
  47183. var indices = [];
  47184. var index = 0;
  47185. for (var count = 0; count < this._capacity; count++) {
  47186. indices.push(index);
  47187. indices.push(index + 1);
  47188. indices.push(index + 2);
  47189. indices.push(index);
  47190. indices.push(index + 2);
  47191. indices.push(index + 3);
  47192. index += 4;
  47193. }
  47194. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47195. };
  47196. /**
  47197. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47198. * Its lifetime will start back at 0.
  47199. * @param particle The particle to recycle
  47200. */
  47201. ParticleSystem.prototype.recycleParticle = function (particle) {
  47202. var lastParticle = this._particles.pop();
  47203. if (lastParticle !== particle) {
  47204. lastParticle.copyTo(particle);
  47205. this._stockParticles.push(lastParticle);
  47206. }
  47207. };
  47208. /**
  47209. * Gets the maximum number of particles active at the same time.
  47210. * @returns The max number of active particles.
  47211. */
  47212. ParticleSystem.prototype.getCapacity = function () {
  47213. return this._capacity;
  47214. };
  47215. /**
  47216. * Gets Wether there are still active particles in the system.
  47217. * @returns True if it is alive, otherwise false.
  47218. */
  47219. ParticleSystem.prototype.isAlive = function () {
  47220. return this._alive;
  47221. };
  47222. /**
  47223. * Gets Wether the system has been started.
  47224. * @returns True if it has been started, otherwise false.
  47225. */
  47226. ParticleSystem.prototype.isStarted = function () {
  47227. return this._started;
  47228. };
  47229. /**
  47230. * Starts the particle system and begins to emit.
  47231. */
  47232. ParticleSystem.prototype.start = function () {
  47233. this._started = true;
  47234. this._stopped = false;
  47235. this._actualFrame = 0;
  47236. };
  47237. /**
  47238. * Stops the particle system.
  47239. */
  47240. ParticleSystem.prototype.stop = function () {
  47241. this._stopped = true;
  47242. };
  47243. /**
  47244. * @ignore (for internal use only)
  47245. */
  47246. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47247. var offset = index * this._vertexBufferSize;
  47248. this._vertexData[offset] = particle.position.x;
  47249. this._vertexData[offset + 1] = particle.position.y;
  47250. this._vertexData[offset + 2] = particle.position.z;
  47251. this._vertexData[offset + 3] = particle.color.r;
  47252. this._vertexData[offset + 4] = particle.color.g;
  47253. this._vertexData[offset + 5] = particle.color.b;
  47254. this._vertexData[offset + 6] = particle.color.a;
  47255. this._vertexData[offset + 7] = particle.angle;
  47256. this._vertexData[offset + 8] = particle.size;
  47257. this._vertexData[offset + 9] = offsetX;
  47258. this._vertexData[offset + 10] = offsetY;
  47259. };
  47260. /**
  47261. * @ignore (for internal use only)
  47262. */
  47263. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47264. if (offsetX === 0)
  47265. offsetX = this._epsilon;
  47266. else if (offsetX === 1)
  47267. offsetX = 1 - this._epsilon;
  47268. if (offsetY === 0)
  47269. offsetY = this._epsilon;
  47270. else if (offsetY === 1)
  47271. offsetY = 1 - this._epsilon;
  47272. var offset = index * this._vertexBufferSize;
  47273. this._vertexData[offset] = particle.position.x;
  47274. this._vertexData[offset + 1] = particle.position.y;
  47275. this._vertexData[offset + 2] = particle.position.z;
  47276. this._vertexData[offset + 3] = particle.color.r;
  47277. this._vertexData[offset + 4] = particle.color.g;
  47278. this._vertexData[offset + 5] = particle.color.b;
  47279. this._vertexData[offset + 6] = particle.color.a;
  47280. this._vertexData[offset + 7] = particle.angle;
  47281. this._vertexData[offset + 8] = particle.size;
  47282. this._vertexData[offset + 9] = offsetX;
  47283. this._vertexData[offset + 10] = offsetY;
  47284. this._vertexData[offset + 11] = particle.cellIndex;
  47285. };
  47286. ParticleSystem.prototype._update = function (newParticles) {
  47287. // Update current
  47288. this._alive = this._particles.length > 0;
  47289. this.updateFunction(this._particles);
  47290. // Add new ones
  47291. var worldMatrix;
  47292. if (this.emitter.position) {
  47293. var emitterMesh = this.emitter;
  47294. worldMatrix = emitterMesh.getWorldMatrix();
  47295. }
  47296. else {
  47297. var emitterPosition = this.emitter;
  47298. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47299. }
  47300. var particle;
  47301. for (var index = 0; index < newParticles; index++) {
  47302. if (this._particles.length === this._capacity) {
  47303. break;
  47304. }
  47305. if (this._stockParticles.length !== 0) {
  47306. particle = this._stockParticles.pop();
  47307. particle.age = 0;
  47308. particle.cellIndex = this.startSpriteCellID;
  47309. }
  47310. else {
  47311. particle = new BABYLON.Particle(this);
  47312. }
  47313. this._particles.push(particle);
  47314. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47315. if (this.startPositionFunction) {
  47316. this.startPositionFunction(worldMatrix, particle.position, particle);
  47317. }
  47318. else {
  47319. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47320. }
  47321. if (this.startDirectionFunction) {
  47322. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47323. }
  47324. else {
  47325. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47326. }
  47327. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47328. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47329. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47330. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47331. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47332. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47333. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47334. }
  47335. };
  47336. ParticleSystem.prototype._getEffect = function () {
  47337. if (this._customEffect) {
  47338. return this._customEffect;
  47339. }
  47340. ;
  47341. var defines = [];
  47342. if (this._scene.clipPlane) {
  47343. defines.push("#define CLIPPLANE");
  47344. }
  47345. if (this._isAnimationSheetEnabled) {
  47346. defines.push("#define ANIMATESHEET");
  47347. }
  47348. // Effect
  47349. var join = defines.join("\n");
  47350. if (this._cachedDefines !== join) {
  47351. this._cachedDefines = join;
  47352. var attributesNamesOrOptions;
  47353. var effectCreationOption;
  47354. if (this._isAnimationSheetEnabled) {
  47355. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47356. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47357. }
  47358. else {
  47359. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47360. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47361. }
  47362. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47363. }
  47364. return this._effect;
  47365. };
  47366. /**
  47367. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47368. */
  47369. ParticleSystem.prototype.animate = function () {
  47370. if (!this._started)
  47371. return;
  47372. var effect = this._getEffect();
  47373. // Check
  47374. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47375. return;
  47376. if (this._currentRenderId === this._scene.getRenderId()) {
  47377. return;
  47378. }
  47379. this._currentRenderId = this._scene.getRenderId();
  47380. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47381. // determine the number of particles we need to create
  47382. var newParticles;
  47383. if (this.manualEmitCount > -1) {
  47384. newParticles = this.manualEmitCount;
  47385. this._newPartsExcess = 0;
  47386. this.manualEmitCount = 0;
  47387. }
  47388. else {
  47389. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47390. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47391. }
  47392. if (this._newPartsExcess > 1.0) {
  47393. newParticles += this._newPartsExcess >> 0;
  47394. this._newPartsExcess -= this._newPartsExcess >> 0;
  47395. }
  47396. this._alive = false;
  47397. if (!this._stopped) {
  47398. this._actualFrame += this._scaledUpdateSpeed;
  47399. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47400. this.stop();
  47401. }
  47402. else {
  47403. newParticles = 0;
  47404. }
  47405. this._update(newParticles);
  47406. // Stopped?
  47407. if (this._stopped) {
  47408. if (!this._alive) {
  47409. this._started = false;
  47410. if (this.onAnimationEnd) {
  47411. this.onAnimationEnd();
  47412. }
  47413. if (this.disposeOnStop) {
  47414. this._scene._toBeDisposed.push(this);
  47415. }
  47416. }
  47417. }
  47418. // Animation sheet
  47419. if (this._isAnimationSheetEnabled) {
  47420. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47421. }
  47422. else {
  47423. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47424. }
  47425. // Update VBO
  47426. var offset = 0;
  47427. for (var index = 0; index < this._particles.length; index++) {
  47428. var particle = this._particles[index];
  47429. this._appendParticleVertexes(offset, particle);
  47430. offset += 4;
  47431. }
  47432. if (this._vertexBuffer) {
  47433. this._vertexBuffer.update(this._vertexData);
  47434. }
  47435. };
  47436. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47437. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47438. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47439. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47440. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47441. };
  47442. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47443. this._appendParticleVertex(offset++, particle, 0, 0);
  47444. this._appendParticleVertex(offset++, particle, 1, 0);
  47445. this._appendParticleVertex(offset++, particle, 1, 1);
  47446. this._appendParticleVertex(offset++, particle, 0, 1);
  47447. };
  47448. /**
  47449. * Rebuilds the particle system.
  47450. */
  47451. ParticleSystem.prototype.rebuild = function () {
  47452. this._createIndexBuffer();
  47453. if (this._vertexBuffer) {
  47454. this._vertexBuffer._rebuild();
  47455. }
  47456. };
  47457. /**
  47458. * Renders the particle system in its current state.
  47459. * @returns the current number of particles.
  47460. */
  47461. ParticleSystem.prototype.render = function () {
  47462. var effect = this._getEffect();
  47463. // Check
  47464. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47465. return 0;
  47466. var engine = this._scene.getEngine();
  47467. // Render
  47468. engine.enableEffect(effect);
  47469. engine.setState(false);
  47470. var viewMatrix = this._scene.getViewMatrix();
  47471. effect.setTexture("diffuseSampler", this.particleTexture);
  47472. effect.setMatrix("view", viewMatrix);
  47473. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47474. if (this._isAnimationSheetEnabled) {
  47475. var baseSize = this.particleTexture.getBaseSize();
  47476. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47477. }
  47478. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47479. if (this._scene.clipPlane) {
  47480. var clipPlane = this._scene.clipPlane;
  47481. var invView = viewMatrix.clone();
  47482. invView.invert();
  47483. effect.setMatrix("invView", invView);
  47484. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47485. }
  47486. // VBOs
  47487. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47488. // Draw order
  47489. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47490. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47491. }
  47492. else {
  47493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47494. }
  47495. if (this.forceDepthWrite) {
  47496. engine.setDepthWrite(true);
  47497. }
  47498. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47500. return this._particles.length;
  47501. };
  47502. /**
  47503. * Disposes the particle system and free the associated resources.
  47504. */
  47505. ParticleSystem.prototype.dispose = function () {
  47506. if (this._vertexBuffer) {
  47507. this._vertexBuffer.dispose();
  47508. this._vertexBuffer = null;
  47509. }
  47510. if (this._indexBuffer) {
  47511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47512. this._indexBuffer = null;
  47513. }
  47514. if (this.particleTexture) {
  47515. this.particleTexture.dispose();
  47516. this.particleTexture = null;
  47517. }
  47518. // Remove from scene
  47519. var index = this._scene.particleSystems.indexOf(this);
  47520. if (index > -1) {
  47521. this._scene.particleSystems.splice(index, 1);
  47522. }
  47523. // Callback
  47524. this.onDisposeObservable.notifyObservers(this);
  47525. this.onDisposeObservable.clear();
  47526. };
  47527. /**
  47528. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  47529. * @param radius The radius of the sphere to emit from
  47530. * @returns the emitter
  47531. */
  47532. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  47533. if (radius === void 0) { radius = 1; }
  47534. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  47535. this.particleEmitterType = particleEmitter;
  47536. return particleEmitter;
  47537. };
  47538. /**
  47539. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  47540. * @param radius The radius of the sphere to emit from
  47541. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  47542. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  47543. * @returns the emitter
  47544. */
  47545. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  47546. if (radius === void 0) { radius = 1; }
  47547. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  47548. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  47549. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  47550. this.particleEmitterType = particleEmitter;
  47551. return particleEmitter;
  47552. };
  47553. /**
  47554. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  47555. * @param radius The radius of the cone to emit from
  47556. * @param angle The base angle of the cone
  47557. * @returns the emitter
  47558. */
  47559. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  47560. if (radius === void 0) { radius = 1; }
  47561. if (angle === void 0) { angle = Math.PI / 4; }
  47562. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  47563. this.particleEmitterType = particleEmitter;
  47564. return particleEmitter;
  47565. };
  47566. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  47567. /**
  47568. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  47569. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  47570. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  47571. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47572. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47573. * @returns the emitter
  47574. */
  47575. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  47576. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  47577. this.direction1 = direction1;
  47578. this.direction2 = direction2;
  47579. this.minEmitBox = minEmitBox;
  47580. this.maxEmitBox = maxEmitBox;
  47581. this.particleEmitterType = particleEmitter;
  47582. return particleEmitter;
  47583. };
  47584. /**
  47585. * Clones the particle system.
  47586. * @param name The name of the cloned object
  47587. * @param newEmitter The new emitter to use
  47588. * @returns the cloned particle system
  47589. */
  47590. ParticleSystem.prototype.clone = function (name, newEmitter) {
  47591. var custom = null;
  47592. var program = null;
  47593. if (this.customShader != null) {
  47594. program = this.customShader;
  47595. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47596. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47597. }
  47598. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  47599. result.customShader = program;
  47600. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  47601. if (newEmitter === undefined) {
  47602. newEmitter = this.emitter;
  47603. }
  47604. result.emitter = newEmitter;
  47605. if (this.particleTexture) {
  47606. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  47607. }
  47608. if (!this.preventAutoStart) {
  47609. result.start();
  47610. }
  47611. return result;
  47612. };
  47613. /**
  47614. * Serializes the particle system to a JSON object.
  47615. * @returns the JSON object
  47616. */
  47617. ParticleSystem.prototype.serialize = function () {
  47618. var serializationObject = {};
  47619. serializationObject.name = this.name;
  47620. serializationObject.id = this.id;
  47621. // Emitter
  47622. if (this.emitter.position) {
  47623. var emitterMesh = this.emitter;
  47624. serializationObject.emitterId = emitterMesh.id;
  47625. }
  47626. else {
  47627. var emitterPosition = this.emitter;
  47628. serializationObject.emitter = emitterPosition.asArray();
  47629. }
  47630. serializationObject.capacity = this.getCapacity();
  47631. if (this.particleTexture) {
  47632. serializationObject.textureName = this.particleTexture.name;
  47633. }
  47634. // Animations
  47635. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  47636. // Particle system
  47637. serializationObject.minAngularSpeed = this.minAngularSpeed;
  47638. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  47639. serializationObject.minSize = this.minSize;
  47640. serializationObject.maxSize = this.maxSize;
  47641. serializationObject.minEmitPower = this.minEmitPower;
  47642. serializationObject.maxEmitPower = this.maxEmitPower;
  47643. serializationObject.minLifeTime = this.minLifeTime;
  47644. serializationObject.maxLifeTime = this.maxLifeTime;
  47645. serializationObject.emitRate = this.emitRate;
  47646. serializationObject.minEmitBox = this.minEmitBox.asArray();
  47647. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  47648. serializationObject.gravity = this.gravity.asArray();
  47649. serializationObject.direction1 = this.direction1.asArray();
  47650. serializationObject.direction2 = this.direction2.asArray();
  47651. serializationObject.color1 = this.color1.asArray();
  47652. serializationObject.color2 = this.color2.asArray();
  47653. serializationObject.colorDead = this.colorDead.asArray();
  47654. serializationObject.updateSpeed = this.updateSpeed;
  47655. serializationObject.targetStopDuration = this.targetStopDuration;
  47656. serializationObject.textureMask = this.textureMask.asArray();
  47657. serializationObject.blendMode = this.blendMode;
  47658. serializationObject.customShader = this.customShader;
  47659. serializationObject.preventAutoStart = this.preventAutoStart;
  47660. serializationObject.startSpriteCellID = this.startSpriteCellID;
  47661. serializationObject.endSpriteCellID = this.endSpriteCellID;
  47662. serializationObject.spriteCellLoop = this.spriteCellLoop;
  47663. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  47664. serializationObject.spriteCellWidth = this.spriteCellWidth;
  47665. serializationObject.spriteCellHeight = this.spriteCellHeight;
  47666. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  47667. return serializationObject;
  47668. };
  47669. /**
  47670. * Parses a JSON object to create a particle system.
  47671. * @param parsedParticleSystem The JSON object to parse
  47672. * @param scene The scene to create the particle system in
  47673. * @param rootUrl The root url to use to load external dependencies like texture
  47674. * @returns the Parsed particle system
  47675. */
  47676. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  47677. var name = parsedParticleSystem.name;
  47678. var custom = null;
  47679. var program = null;
  47680. if (parsedParticleSystem.customShader) {
  47681. program = parsedParticleSystem.customShader;
  47682. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47683. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47684. }
  47685. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  47686. particleSystem.customShader = program;
  47687. if (parsedParticleSystem.id) {
  47688. particleSystem.id = parsedParticleSystem.id;
  47689. }
  47690. // Auto start
  47691. if (parsedParticleSystem.preventAutoStart) {
  47692. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  47693. }
  47694. // Texture
  47695. if (parsedParticleSystem.textureName) {
  47696. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  47697. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  47698. }
  47699. // Emitter
  47700. if (parsedParticleSystem.emitterId) {
  47701. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  47702. }
  47703. else {
  47704. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  47705. }
  47706. // Animations
  47707. if (parsedParticleSystem.animations) {
  47708. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  47709. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  47710. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  47711. }
  47712. }
  47713. if (parsedParticleSystem.autoAnimate) {
  47714. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  47715. }
  47716. // Particle system
  47717. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  47718. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  47719. particleSystem.minSize = parsedParticleSystem.minSize;
  47720. particleSystem.maxSize = parsedParticleSystem.maxSize;
  47721. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  47722. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  47723. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  47724. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  47725. particleSystem.emitRate = parsedParticleSystem.emitRate;
  47726. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  47727. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  47728. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  47729. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  47730. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  47731. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  47732. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  47733. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  47734. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  47735. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  47736. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  47737. particleSystem.blendMode = parsedParticleSystem.blendMode;
  47738. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  47739. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  47740. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  47741. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  47742. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  47743. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  47744. if (!particleSystem.preventAutoStart) {
  47745. particleSystem.start();
  47746. }
  47747. return particleSystem;
  47748. };
  47749. /**
  47750. * Source color is added to the destination color without alpha affecting the result.
  47751. */
  47752. ParticleSystem.BLENDMODE_ONEONE = 0;
  47753. /**
  47754. * Blend current color and particle color using particle’s alpha.
  47755. */
  47756. ParticleSystem.BLENDMODE_STANDARD = 1;
  47757. return ParticleSystem;
  47758. }());
  47759. BABYLON.ParticleSystem = ParticleSystem;
  47760. })(BABYLON || (BABYLON = {}));
  47761. //# sourceMappingURL=babylon.particleSystem.js.map
  47762. var BABYLON;
  47763. (function (BABYLON) {
  47764. /**
  47765. * Particle emitter emitting particles from the inside of a box.
  47766. * It emits the particles randomly between 2 given directions.
  47767. */
  47768. var BoxParticleEmitter = /** @class */ (function () {
  47769. // to be updated like the rest of emitters when breaking changes.
  47770. // all property should be come public variables and passed through constructor.
  47771. /**
  47772. * Creates a new instance of @see BoxParticleEmitter
  47773. * @param _particleSystem the particle system associated with the emitter
  47774. */
  47775. function BoxParticleEmitter(_particleSystem) {
  47776. this._particleSystem = _particleSystem;
  47777. }
  47778. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  47779. /**
  47780. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47781. */
  47782. get: function () {
  47783. return this._particleSystem.direction1;
  47784. },
  47785. /**
  47786. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47787. */
  47788. set: function (value) {
  47789. this._particleSystem.direction1 = value;
  47790. },
  47791. enumerable: true,
  47792. configurable: true
  47793. });
  47794. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  47795. /**
  47796. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47797. */
  47798. get: function () {
  47799. return this._particleSystem.direction2;
  47800. },
  47801. /**
  47802. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47803. */
  47804. set: function (value) {
  47805. this._particleSystem.direction2 = value;
  47806. },
  47807. enumerable: true,
  47808. configurable: true
  47809. });
  47810. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  47811. /**
  47812. * 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.
  47813. */
  47814. get: function () {
  47815. return this._particleSystem.minEmitBox;
  47816. },
  47817. /**
  47818. * 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.
  47819. */
  47820. set: function (value) {
  47821. this._particleSystem.minEmitBox = value;
  47822. },
  47823. enumerable: true,
  47824. configurable: true
  47825. });
  47826. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  47827. /**
  47828. * 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.
  47829. */
  47830. get: function () {
  47831. return this._particleSystem.maxEmitBox;
  47832. },
  47833. /**
  47834. * 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.
  47835. */
  47836. set: function (value) {
  47837. this._particleSystem.maxEmitBox = value;
  47838. },
  47839. enumerable: true,
  47840. configurable: true
  47841. });
  47842. /**
  47843. * Called by the particle System when the direction is computed for the created particle.
  47844. * @param emitPower is the power of the particle (speed)
  47845. * @param worldMatrix is the world matrix of the particle system
  47846. * @param directionToUpdate is the direction vector to update with the result
  47847. * @param particle is the particle we are computed the direction for
  47848. */
  47849. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  47850. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  47851. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  47852. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  47853. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  47854. };
  47855. /**
  47856. * Called by the particle System when the position is computed for the created particle.
  47857. * @param worldMatrix is the world matrix of the particle system
  47858. * @param positionToUpdate is the position vector to update with the result
  47859. * @param particle is the particle we are computed the position for
  47860. */
  47861. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  47862. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  47863. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  47864. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  47865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  47866. };
  47867. return BoxParticleEmitter;
  47868. }());
  47869. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  47870. })(BABYLON || (BABYLON = {}));
  47871. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  47872. var BABYLON;
  47873. (function (BABYLON) {
  47874. /**
  47875. * Particle emitter emitting particles from the inside of a cone.
  47876. * It emits the particles alongside the cone volume from the base to the particle.
  47877. * The emission direction might be randomized.
  47878. */
  47879. var ConeParticleEmitter = /** @class */ (function () {
  47880. /**
  47881. * Creates a new instance of @see ConeParticleEmitter
  47882. * @param radius the radius of the emission cone
  47883. * @param angles the cone base angle
  47884. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  47885. */
  47886. function ConeParticleEmitter(radius,
  47887. /**
  47888. * The radius of the emission cone.
  47889. */
  47890. angle,
  47891. /**
  47892. * The cone base angle.
  47893. */
  47894. directionRandomizer) {
  47895. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  47896. this.angle = angle;
  47897. this.directionRandomizer = directionRandomizer;
  47898. this.radius = radius;
  47899. }
  47900. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  47901. /**
  47902. * Gets the radius of the emission cone.
  47903. */
  47904. get: function () {
  47905. return this._radius;
  47906. },
  47907. /**
  47908. * Sets the radius of the emission cone.
  47909. */
  47910. set: function (value) {
  47911. this._radius = value;
  47912. if (this.angle !== 0) {
  47913. this._height = value / Math.tan(this.angle / 2);
  47914. }
  47915. else {
  47916. this._height = 1;
  47917. }
  47918. },
  47919. enumerable: true,
  47920. configurable: true
  47921. });
  47922. /**
  47923. * Called by the particle System when the direction is computed for the created particle.
  47924. * @param emitPower is the power of the particle (speed)
  47925. * @param worldMatrix is the world matrix of the particle system
  47926. * @param directionToUpdate is the direction vector to update with the result
  47927. * @param particle is the particle we are computed the direction for
  47928. */
  47929. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  47930. if (this.angle === 0) {
  47931. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  47932. }
  47933. else {
  47934. // measure the direction Vector from the emitter to the particle.
  47935. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  47936. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  47937. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  47938. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  47939. direction.x += randX;
  47940. direction.y += randY;
  47941. direction.z += randZ;
  47942. direction.normalize();
  47943. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  47944. }
  47945. };
  47946. /**
  47947. * Called by the particle System when the position is computed for the created particle.
  47948. * @param worldMatrix is the world matrix of the particle system
  47949. * @param positionToUpdate is the position vector to update with the result
  47950. * @param particle is the particle we are computed the position for
  47951. */
  47952. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  47953. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  47954. var h = BABYLON.Scalar.RandomRange(0, 1);
  47955. // Better distribution in a cone at normal angles.
  47956. h = 1 - h * h;
  47957. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  47958. radius = radius * h / this._height;
  47959. var randX = radius * Math.sin(s);
  47960. var randZ = radius * Math.cos(s);
  47961. var randY = h;
  47962. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  47963. };
  47964. return ConeParticleEmitter;
  47965. }());
  47966. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  47967. })(BABYLON || (BABYLON = {}));
  47968. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  47969. var BABYLON;
  47970. (function (BABYLON) {
  47971. /**
  47972. * Particle emitter emitting particles from the inside of a sphere.
  47973. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  47974. */
  47975. var SphereParticleEmitter = /** @class */ (function () {
  47976. /**
  47977. * Creates a new instance of @see SphereParticleEmitter
  47978. * @param radius the radius of the emission sphere
  47979. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  47980. */
  47981. function SphereParticleEmitter(
  47982. /**
  47983. * The radius of the emission sphere.
  47984. */
  47985. radius,
  47986. /**
  47987. * How much to randomize the particle direction [0-1].
  47988. */
  47989. directionRandomizer) {
  47990. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  47991. this.radius = radius;
  47992. this.directionRandomizer = directionRandomizer;
  47993. }
  47994. /**
  47995. * Called by the particle System when the direction is computed for the created particle.
  47996. * @param emitPower is the power of the particle (speed)
  47997. * @param worldMatrix is the world matrix of the particle system
  47998. * @param directionToUpdate is the direction vector to update with the result
  47999. * @param particle is the particle we are computed the direction for
  48000. */
  48001. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48002. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48003. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48004. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48005. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48006. direction.x += randX;
  48007. direction.y += randY;
  48008. direction.z += randZ;
  48009. direction.normalize();
  48010. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48011. };
  48012. /**
  48013. * Called by the particle System when the position is computed for the created particle.
  48014. * @param worldMatrix is the world matrix of the particle system
  48015. * @param positionToUpdate is the position vector to update with the result
  48016. * @param particle is the particle we are computed the position for
  48017. */
  48018. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48019. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48020. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48021. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48022. var randY = this.radius * Math.cos(theta);
  48023. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48025. };
  48026. return SphereParticleEmitter;
  48027. }());
  48028. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48029. /**
  48030. * Particle emitter emitting particles from the inside of a sphere.
  48031. * It emits the particles randomly between two vectors.
  48032. */
  48033. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48034. __extends(SphereDirectedParticleEmitter, _super);
  48035. /**
  48036. * Creates a new instance of @see SphereDirectedParticleEmitter
  48037. * @param radius the radius of the emission sphere
  48038. * @param direction1 the min limit of the emission direction
  48039. * @param direction2 the max limit of the emission direction
  48040. */
  48041. function SphereDirectedParticleEmitter(radius,
  48042. /**
  48043. * The min limit of the emission direction.
  48044. */
  48045. direction1,
  48046. /**
  48047. * The max limit of the emission direction.
  48048. */
  48049. direction2) {
  48050. var _this = _super.call(this, radius) || this;
  48051. _this.direction1 = direction1;
  48052. _this.direction2 = direction2;
  48053. return _this;
  48054. }
  48055. /**
  48056. * Called by the particle System when the direction is computed for the created particle.
  48057. * @param emitPower is the power of the particle (speed)
  48058. * @param worldMatrix is the world matrix of the particle system
  48059. * @param directionToUpdate is the direction vector to update with the result
  48060. * @param particle is the particle we are computed the direction for
  48061. */
  48062. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48063. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48064. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48065. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48066. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48067. };
  48068. return SphereDirectedParticleEmitter;
  48069. }(SphereParticleEmitter));
  48070. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48071. })(BABYLON || (BABYLON = {}));
  48072. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48073. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48074. var BABYLON;
  48075. (function (BABYLON) {
  48076. /**
  48077. * This represents a GPU particle system in Babylon.
  48078. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  48079. */
  48080. var GPUParticleSystem = /** @class */ (function () {
  48081. /**
  48082. * Instantiates a GPU particle system.
  48083. * 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.
  48084. * @param name The name of the particle system
  48085. * @param capacity The max number of particles alive at the same time
  48086. * @param scene The scene the particle system belongs to
  48087. */
  48088. function GPUParticleSystem(name, capacity, scene) {
  48089. /**
  48090. * The emitter represents the Mesh or position we are attaching the particle system to.
  48091. */
  48092. this.emitter = null;
  48093. /**
  48094. * The rendering group used by the Particle system to chose when to render.
  48095. */
  48096. this.renderingGroupId = 0;
  48097. /**
  48098. * The layer mask we are rendering the particles through.
  48099. */
  48100. this.layerMask = 0x0FFFFFFF; // TODO
  48101. this._updateVertexBuffers = {};
  48102. this._renderVertexBuffers = {};
  48103. this._currentRenderId = -1;
  48104. this._started = true;
  48105. /**
  48106. * An event triggered when the system is disposed.
  48107. */
  48108. this.onDisposeObservable = new BABYLON.Observable();
  48109. this.id = name;
  48110. this.name = name;
  48111. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48112. this._capacity = capacity;
  48113. this._engine = this._scene.getEngine();
  48114. this._scene.particleSystems.push(this);
  48115. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  48116. var updateEffectOptions = {
  48117. attributes: ["position", "age", "life", "velocity"],
  48118. uniformsNames: [],
  48119. uniformBuffersNames: [],
  48120. samplers: [],
  48121. defines: "",
  48122. fallbacks: null,
  48123. onCompiled: null,
  48124. onError: null,
  48125. indexParameters: null,
  48126. maxSimultaneousLights: 0,
  48127. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  48128. };
  48129. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  48130. }
  48131. /**
  48132. * Gets Wether the system has been started.
  48133. * @returns True if it has been started, otherwise false.
  48134. */
  48135. GPUParticleSystem.prototype.isStarted = function () {
  48136. return this._started;
  48137. };
  48138. /**
  48139. * Starts the particle system and begins to emit.
  48140. */
  48141. GPUParticleSystem.prototype.start = function () {
  48142. this._started = true;
  48143. };
  48144. /**
  48145. * Stops the particle system.
  48146. */
  48147. GPUParticleSystem.prototype.stop = function () {
  48148. this._started = false;
  48149. };
  48150. /**
  48151. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48152. */
  48153. GPUParticleSystem.prototype.animate = function () {
  48154. // Do nothing
  48155. };
  48156. GPUParticleSystem.prototype._initialize = function () {
  48157. if (this._renderVAO) {
  48158. return;
  48159. }
  48160. var data = new Array();
  48161. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  48162. // position
  48163. data.push(0.0);
  48164. data.push(0.0);
  48165. data.push(0.0);
  48166. var life = 1 + Math.random() * 10; // TODO: var
  48167. data.push(life + 1); // create the particle as a dead one to create a new one at start
  48168. data.push(life);
  48169. // velocity
  48170. data.push(0.0);
  48171. data.push(0.0);
  48172. data.push(0.0);
  48173. }
  48174. // Update VAO
  48175. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48176. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  48177. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  48178. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  48179. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48180. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  48181. this._engine.bindArrayBuffer(null);
  48182. // Render VAO
  48183. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48184. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  48185. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  48186. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  48187. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48188. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  48189. this._engine.bindArrayBuffer(null);
  48190. // Links
  48191. this._sourceVAO = this._updateVAO;
  48192. this._targetVAO = this._renderVAO;
  48193. this._sourceBuffer = this._updateBuffer;
  48194. this._targetBuffer = this._renderBuffer;
  48195. };
  48196. /**
  48197. * Renders the particle system in its current state.
  48198. * @returns the current number of particles.
  48199. */
  48200. GPUParticleSystem.prototype.render = function () {
  48201. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  48202. return 0;
  48203. }
  48204. // Get everything ready to render
  48205. this._initialize();
  48206. if (this._currentRenderId === this._scene.getRenderId()) {
  48207. return 0;
  48208. }
  48209. this._currentRenderId = this._scene.getRenderId();
  48210. // Enable update effect
  48211. this._engine.enableEffect(this._updateEffect);
  48212. this._engine.setState(false);
  48213. // Bind source VAO
  48214. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  48215. // Update
  48216. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  48217. this._engine.setRasterizerState(false);
  48218. this._engine.beginTransformFeedback();
  48219. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48220. this._engine.endTransformFeedback();
  48221. this._engine.setRasterizerState(true);
  48222. this._engine.bindTransformFeedbackBuffer(null);
  48223. // Enable render effect
  48224. this._engine.enableEffect(this._renderEffect);
  48225. // Bind source VAO
  48226. this._engine.bindVertexArrayObject(this._targetVAO, null);
  48227. // Render
  48228. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48229. // Switch VAOs
  48230. var tmpVAO = this._sourceVAO;
  48231. this._sourceVAO = this._targetVAO;
  48232. this._targetVAO = tmpVAO;
  48233. // Switch buffers
  48234. var tmpBuffer = this._sourceBuffer;
  48235. this._sourceBuffer = this._targetBuffer;
  48236. this._targetBuffer = tmpBuffer;
  48237. return 0;
  48238. };
  48239. /**
  48240. * Rebuilds the particle system
  48241. */
  48242. GPUParticleSystem.prototype.rebuild = function () {
  48243. };
  48244. /**
  48245. * Disposes the particle system and free the associated resources.
  48246. */
  48247. GPUParticleSystem.prototype.dispose = function () {
  48248. var index = this._scene.particleSystems.indexOf(this);
  48249. if (index > -1) {
  48250. this._scene.particleSystems.splice(index, 1);
  48251. }
  48252. //TODO: this._dataBuffer.dispose();
  48253. // Callback
  48254. this.onDisposeObservable.notifyObservers(this);
  48255. this.onDisposeObservable.clear();
  48256. };
  48257. //TODO: Clone / Parse / serialize
  48258. /**
  48259. * Clones the particle system.
  48260. * @param name The name of the cloned object
  48261. * @param newEmitter The new emitter to use
  48262. * @returns the cloned particle system
  48263. */
  48264. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  48265. return null;
  48266. };
  48267. /**
  48268. * Serializes the particle system to a JSON object.
  48269. * @returns the JSON object
  48270. */
  48271. GPUParticleSystem.prototype.serialize = function () {
  48272. };
  48273. return GPUParticleSystem;
  48274. }());
  48275. BABYLON.GPUParticleSystem = GPUParticleSystem;
  48276. })(BABYLON || (BABYLON = {}));
  48277. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  48278. var BABYLON;
  48279. (function (BABYLON) {
  48280. /**
  48281. * Represents one particle of a solid particle system.
  48282. * @see SolidParticleSystem
  48283. */
  48284. var SolidParticle = /** @class */ (function () {
  48285. /**
  48286. * Creates a Solid Particle object.
  48287. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48288. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48289. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48290. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48291. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48292. * @param shapeId (integer) is the model shape identifier in the SPS.
  48293. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48294. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48295. */
  48296. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48297. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48298. /**
  48299. * particle global index
  48300. */
  48301. this.idx = 0;
  48302. /**
  48303. * The color of the particle
  48304. */
  48305. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48306. /**
  48307. * The world space position of the particle.
  48308. */
  48309. this.position = BABYLON.Vector3.Zero();
  48310. /**
  48311. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48312. */
  48313. this.rotation = BABYLON.Vector3.Zero();
  48314. /**
  48315. * The scaling of the particle.
  48316. */
  48317. this.scaling = BABYLON.Vector3.One();
  48318. /**
  48319. * The uvs of the particle.
  48320. */
  48321. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48322. /**
  48323. * The current speed of the particle.
  48324. */
  48325. this.velocity = BABYLON.Vector3.Zero();
  48326. /**
  48327. * The pivot point in the particle local space.
  48328. */
  48329. this.pivot = BABYLON.Vector3.Zero();
  48330. /**
  48331. * Is the particle active or not ?
  48332. */
  48333. this.alive = true;
  48334. /**
  48335. * Is the particle visible or not ?
  48336. */
  48337. this.isVisible = true;
  48338. /**
  48339. * Index of this particle in the global "positions" array (Internal use)
  48340. */
  48341. this._pos = 0;
  48342. /**
  48343. * Index of this particle in the global "indices" array (Internal use)
  48344. */
  48345. this._ind = 0;
  48346. /**
  48347. * ModelShape id of this particle
  48348. */
  48349. this.shapeId = 0;
  48350. /**
  48351. * Index of the particle in its shape id (Internal use)
  48352. */
  48353. this.idxInShape = 0;
  48354. /**
  48355. * Still set as invisible in order to skip useless computations (Internal use)
  48356. */
  48357. this._stillInvisible = false;
  48358. this.idx = particleIndex;
  48359. this._pos = positionIndex;
  48360. this._ind = indiceIndex;
  48361. this._model = model;
  48362. this.shapeId = shapeId;
  48363. this.idxInShape = idxInShape;
  48364. this._sps = sps;
  48365. if (modelBoundingInfo) {
  48366. this._modelBoundingInfo = modelBoundingInfo;
  48367. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48368. }
  48369. }
  48370. Object.defineProperty(SolidParticle.prototype, "scale", {
  48371. /**
  48372. * Legacy support, changed scale to scaling
  48373. */
  48374. get: function () {
  48375. return this.scaling;
  48376. },
  48377. /**
  48378. * Legacy support, changed scale to scaling
  48379. */
  48380. set: function (scale) {
  48381. this.scaling = scale;
  48382. },
  48383. enumerable: true,
  48384. configurable: true
  48385. });
  48386. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48387. /**
  48388. * Legacy support, changed quaternion to rotationQuaternion
  48389. */
  48390. get: function () {
  48391. return this.rotationQuaternion;
  48392. },
  48393. /**
  48394. * Legacy support, changed quaternion to rotationQuaternion
  48395. */
  48396. set: function (q) {
  48397. this.rotationQuaternion = q;
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. /**
  48403. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48404. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48405. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48406. * @returns true if it intersects
  48407. */
  48408. SolidParticle.prototype.intersectsMesh = function (target) {
  48409. if (!this._boundingInfo || !target._boundingInfo) {
  48410. return false;
  48411. }
  48412. if (this._sps._bSphereOnly) {
  48413. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48414. }
  48415. return this._boundingInfo.intersects(target._boundingInfo, false);
  48416. };
  48417. return SolidParticle;
  48418. }());
  48419. BABYLON.SolidParticle = SolidParticle;
  48420. /**
  48421. * Represents the shape of the model used by one particle of a solid particle system.
  48422. * SPS internal tool, don't use it manually.
  48423. * @see SolidParticleSystem
  48424. */
  48425. var ModelShape = /** @class */ (function () {
  48426. /**
  48427. * 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.
  48428. * SPS internal tool, don't use it manually.
  48429. * @ignore
  48430. */
  48431. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48432. /**
  48433. * length of the shape in the model indices array (internal use)
  48434. */
  48435. this._indicesLength = 0;
  48436. this.shapeID = id;
  48437. this._shape = shape;
  48438. this._indicesLength = indicesLength;
  48439. this._shapeUV = shapeUV;
  48440. this._positionFunction = posFunction;
  48441. this._vertexFunction = vtxFunction;
  48442. }
  48443. return ModelShape;
  48444. }());
  48445. BABYLON.ModelShape = ModelShape;
  48446. /**
  48447. * Represents a Depth Sorted Particle in the solid particle system.
  48448. * @see SolidParticleSystem
  48449. */
  48450. var DepthSortedParticle = /** @class */ (function () {
  48451. function DepthSortedParticle() {
  48452. /**
  48453. * Index of the particle in the "indices" array
  48454. */
  48455. this.ind = 0;
  48456. /**
  48457. * Length of the particle shape in the "indices" array
  48458. */
  48459. this.indicesLength = 0;
  48460. /**
  48461. * Squared distance from the particle to the camera
  48462. */
  48463. this.sqDistance = 0.0;
  48464. }
  48465. return DepthSortedParticle;
  48466. }());
  48467. BABYLON.DepthSortedParticle = DepthSortedParticle;
  48468. })(BABYLON || (BABYLON = {}));
  48469. //# sourceMappingURL=babylon.solidParticle.js.map
  48470. var BABYLON;
  48471. (function (BABYLON) {
  48472. /**
  48473. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  48474. *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.
  48475. * The SPS is also a particle system. It provides some methods to manage the particles.
  48476. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  48477. *
  48478. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48479. */
  48480. var SolidParticleSystem = /** @class */ (function () {
  48481. /**
  48482. * Creates a SPS (Solid Particle System) object.
  48483. * @param name (String) is the SPS name, this will be the underlying mesh name.
  48484. * @param scene (Scene) is the scene in which the SPS is added.
  48485. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  48486. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  48487. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  48488. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  48489. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48490. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48491. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48492. */
  48493. function SolidParticleSystem(name, scene, options) {
  48494. /**
  48495. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48496. * Example : var p = SPS.particles[i];
  48497. */
  48498. this.particles = new Array();
  48499. /**
  48500. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48501. */
  48502. this.nbParticles = 0;
  48503. /**
  48504. * If the particles must ever face the camera (default false). Useful for planar particles.
  48505. */
  48506. this.billboard = false;
  48507. /**
  48508. * Recompute normals when adding a shape
  48509. */
  48510. this.recomputeNormals = true;
  48511. /**
  48512. * This a counter ofr your own usage. It's not set by any SPS functions.
  48513. */
  48514. this.counter = 0;
  48515. /**
  48516. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48517. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48518. */
  48519. this.vars = {};
  48520. /**
  48521. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  48522. */
  48523. this._bSphereOnly = false;
  48524. /**
  48525. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  48526. */
  48527. this._bSphereRadiusFactor = 1.0;
  48528. this._positions = new Array();
  48529. this._indices = new Array();
  48530. this._normals = new Array();
  48531. this._colors = new Array();
  48532. this._uvs = new Array();
  48533. this._index = 0; // indices index
  48534. this._updatable = true;
  48535. this._pickable = false;
  48536. this._isVisibilityBoxLocked = false;
  48537. this._alwaysVisible = false;
  48538. this._depthSort = false;
  48539. this._shapeCounter = 0;
  48540. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  48541. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48542. this._computeParticleColor = true;
  48543. this._computeParticleTexture = true;
  48544. this._computeParticleRotation = true;
  48545. this._computeParticleVertex = false;
  48546. this._computeBoundingBox = false;
  48547. this._depthSortParticles = true;
  48548. this._cam_axisZ = BABYLON.Vector3.Zero();
  48549. this._cam_axisY = BABYLON.Vector3.Zero();
  48550. this._cam_axisX = BABYLON.Vector3.Zero();
  48551. this._axisZ = BABYLON.Axis.Z;
  48552. this._camDir = BABYLON.Vector3.Zero();
  48553. this._camInvertedPosition = BABYLON.Vector3.Zero();
  48554. this._rotMatrix = new BABYLON.Matrix();
  48555. this._invertMatrix = new BABYLON.Matrix();
  48556. this._rotated = BABYLON.Vector3.Zero();
  48557. this._quaternion = new BABYLON.Quaternion();
  48558. this._vertex = BABYLON.Vector3.Zero();
  48559. this._normal = BABYLON.Vector3.Zero();
  48560. this._yaw = 0.0;
  48561. this._pitch = 0.0;
  48562. this._roll = 0.0;
  48563. this._halfroll = 0.0;
  48564. this._halfpitch = 0.0;
  48565. this._halfyaw = 0.0;
  48566. this._sinRoll = 0.0;
  48567. this._cosRoll = 0.0;
  48568. this._sinPitch = 0.0;
  48569. this._cosPitch = 0.0;
  48570. this._sinYaw = 0.0;
  48571. this._cosYaw = 0.0;
  48572. this._mustUnrotateFixedNormals = false;
  48573. this._minimum = BABYLON.Tmp.Vector3[0];
  48574. this._maximum = BABYLON.Tmp.Vector3[1];
  48575. this._minBbox = BABYLON.Tmp.Vector3[4];
  48576. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48577. this._particlesIntersect = false;
  48578. this._depthSortFunction = function (p1, p2) {
  48579. return (p2.sqDistance - p1.sqDistance);
  48580. };
  48581. this._needs32Bits = false;
  48582. this.name = name;
  48583. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48584. this._camera = scene.activeCamera;
  48585. this._pickable = options ? options.isPickable : false;
  48586. this._depthSort = options ? options.enableDepthSort : false;
  48587. this._particlesIntersect = options ? options.particleIntersection : false;
  48588. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48589. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48590. if (options && options.updatable) {
  48591. this._updatable = options.updatable;
  48592. }
  48593. else {
  48594. this._updatable = true;
  48595. }
  48596. if (this._pickable) {
  48597. this.pickedParticles = [];
  48598. }
  48599. if (this._depthSort) {
  48600. this.depthSortedParticles = [];
  48601. }
  48602. }
  48603. /**
  48604. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48605. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48606. * @returns the created mesh
  48607. */
  48608. SolidParticleSystem.prototype.buildMesh = function () {
  48609. if (this.nbParticles === 0) {
  48610. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48611. this.addShape(triangle, 1);
  48612. triangle.dispose();
  48613. }
  48614. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  48615. this._positions32 = new Float32Array(this._positions);
  48616. this._uvs32 = new Float32Array(this._uvs);
  48617. this._colors32 = new Float32Array(this._colors);
  48618. if (this.recomputeNormals) {
  48619. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  48620. }
  48621. this._normals32 = new Float32Array(this._normals);
  48622. this._fixedNormal32 = new Float32Array(this._normals);
  48623. if (this._mustUnrotateFixedNormals) {
  48624. this._unrotateFixedNormals();
  48625. }
  48626. var vertexData = new BABYLON.VertexData();
  48627. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  48628. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48629. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48630. if (this._uvs32) {
  48631. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48632. ;
  48633. }
  48634. if (this._colors32) {
  48635. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48636. }
  48637. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48638. vertexData.applyToMesh(mesh, this._updatable);
  48639. this.mesh = mesh;
  48640. this.mesh.isPickable = this._pickable;
  48641. // free memory
  48642. if (!this._depthSort) {
  48643. this._indices = null;
  48644. }
  48645. this._positions = null;
  48646. this._normals = null;
  48647. this._uvs = null;
  48648. this._colors = null;
  48649. if (!this._updatable) {
  48650. this.particles.length = 0;
  48651. }
  48652. return mesh;
  48653. };
  48654. /**
  48655. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48656. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48657. * Thus the particles generated from `digest()` have their property `position` set yet.
  48658. * @param mesh ( Mesh ) is the mesh to be digested
  48659. * @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
  48660. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48661. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48662. * @returns the current SPS
  48663. */
  48664. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48665. var size = (options && options.facetNb) || 1;
  48666. var number = (options && options.number) || 0;
  48667. var delta = (options && options.delta) || 0;
  48668. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48669. var meshInd = mesh.getIndices();
  48670. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48671. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48672. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48673. var f = 0; // facet counter
  48674. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48675. // compute size from number
  48676. if (number) {
  48677. number = (number > totalFacets) ? totalFacets : number;
  48678. size = Math.round(totalFacets / number);
  48679. delta = 0;
  48680. }
  48681. else {
  48682. size = (size > totalFacets) ? totalFacets : size;
  48683. }
  48684. var facetPos = []; // submesh positions
  48685. var facetInd = []; // submesh indices
  48686. var facetUV = []; // submesh UV
  48687. var facetCol = []; // submesh colors
  48688. var barycenter = BABYLON.Tmp.Vector3[0];
  48689. var sizeO = size;
  48690. while (f < totalFacets) {
  48691. size = sizeO + Math.floor((1 + delta) * Math.random());
  48692. if (f > totalFacets - size) {
  48693. size = totalFacets - f;
  48694. }
  48695. // reset temp arrays
  48696. facetPos.length = 0;
  48697. facetInd.length = 0;
  48698. facetUV.length = 0;
  48699. facetCol.length = 0;
  48700. // iterate over "size" facets
  48701. var fi = 0;
  48702. for (var j = f * 3; j < (f + size) * 3; j++) {
  48703. facetInd.push(fi);
  48704. var i = meshInd[j];
  48705. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48706. if (meshUV) {
  48707. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48708. }
  48709. if (meshCol) {
  48710. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48711. }
  48712. fi++;
  48713. }
  48714. // create a model shape for each single particle
  48715. var idx = this.nbParticles;
  48716. var shape = this._posToShape(facetPos);
  48717. var shapeUV = this._uvsToShapeUV(facetUV);
  48718. // compute the barycenter of the shape
  48719. var v;
  48720. for (v = 0; v < shape.length; v++) {
  48721. barycenter.addInPlace(shape[v]);
  48722. }
  48723. barycenter.scaleInPlace(1 / shape.length);
  48724. // shift the shape from its barycenter to the origin
  48725. for (v = 0; v < shape.length; v++) {
  48726. shape[v].subtractInPlace(barycenter);
  48727. }
  48728. var bInfo;
  48729. if (this._particlesIntersect) {
  48730. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48731. }
  48732. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  48733. // add the particle in the SPS
  48734. var currentPos = this._positions.length;
  48735. var currentInd = this._indices.length;
  48736. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48737. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  48738. // initialize the particle position
  48739. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48740. this._index += shape.length;
  48741. idx++;
  48742. this.nbParticles++;
  48743. this._shapeCounter++;
  48744. f += size;
  48745. }
  48746. return this;
  48747. };
  48748. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  48749. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  48750. var index = 0;
  48751. var idx = 0;
  48752. for (var p = 0; p < this.particles.length; p++) {
  48753. this._particle = this.particles[p];
  48754. this._shape = this._particle._model._shape;
  48755. if (this._particle.rotationQuaternion) {
  48756. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48757. }
  48758. else {
  48759. this._yaw = this._particle.rotation.y;
  48760. this._pitch = this._particle.rotation.x;
  48761. this._roll = this._particle.rotation.z;
  48762. this._quaternionRotationYPR();
  48763. }
  48764. this._quaternionToRotationMatrix();
  48765. this._rotMatrix.invertToRef(this._invertMatrix);
  48766. for (var pt = 0; pt < this._shape.length; pt++) {
  48767. idx = index + pt * 3;
  48768. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  48769. this._fixedNormal32[idx] = this._normal.x;
  48770. this._fixedNormal32[idx + 1] = this._normal.y;
  48771. this._fixedNormal32[idx + 2] = this._normal.z;
  48772. }
  48773. index = idx + 3;
  48774. }
  48775. };
  48776. //reset copy
  48777. SolidParticleSystem.prototype._resetCopy = function () {
  48778. this._copy.position.x = 0;
  48779. this._copy.position.y = 0;
  48780. this._copy.position.z = 0;
  48781. this._copy.rotation.x = 0;
  48782. this._copy.rotation.y = 0;
  48783. this._copy.rotation.z = 0;
  48784. this._copy.rotationQuaternion = null;
  48785. this._copy.scaling.x = 1.0;
  48786. this._copy.scaling.y = 1.0;
  48787. this._copy.scaling.z = 1.0;
  48788. this._copy.uvs.x = 0;
  48789. this._copy.uvs.y = 0;
  48790. this._copy.uvs.z = 1.0;
  48791. this._copy.uvs.w = 1.0;
  48792. this._copy.color = null;
  48793. };
  48794. // _meshBuilder : inserts the shape model in the global SPS mesh
  48795. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48796. var i;
  48797. var u = 0;
  48798. var c = 0;
  48799. var n = 0;
  48800. this._resetCopy();
  48801. if (options && options.positionFunction) {
  48802. options.positionFunction(this._copy, idx, idxInShape);
  48803. this._mustUnrotateFixedNormals = true;
  48804. }
  48805. if (this._copy.rotationQuaternion) {
  48806. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48807. }
  48808. else {
  48809. this._yaw = this._copy.rotation.y;
  48810. this._pitch = this._copy.rotation.x;
  48811. this._roll = this._copy.rotation.z;
  48812. this._quaternionRotationYPR();
  48813. }
  48814. this._quaternionToRotationMatrix();
  48815. for (i = 0; i < shape.length; i++) {
  48816. this._vertex.x = shape[i].x;
  48817. this._vertex.y = shape[i].y;
  48818. this._vertex.z = shape[i].z;
  48819. if (options && options.vertexFunction) {
  48820. options.vertexFunction(this._copy, this._vertex, i);
  48821. }
  48822. this._vertex.x *= this._copy.scaling.x;
  48823. this._vertex.y *= this._copy.scaling.y;
  48824. this._vertex.z *= this._copy.scaling.z;
  48825. this._vertex.x += this._copy.pivot.x;
  48826. this._vertex.y += this._copy.pivot.y;
  48827. this._vertex.z += this._copy.pivot.z;
  48828. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48829. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  48830. if (meshUV) {
  48831. 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);
  48832. u += 2;
  48833. }
  48834. if (this._copy.color) {
  48835. this._color = this._copy.color;
  48836. }
  48837. else if (meshCol && meshCol[c] !== undefined) {
  48838. this._color.r = meshCol[c];
  48839. this._color.g = meshCol[c + 1];
  48840. this._color.b = meshCol[c + 2];
  48841. this._color.a = meshCol[c + 3];
  48842. }
  48843. else {
  48844. this._color.r = 1.0;
  48845. this._color.g = 1.0;
  48846. this._color.b = 1.0;
  48847. this._color.a = 1.0;
  48848. }
  48849. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  48850. c += 4;
  48851. if (!this.recomputeNormals && meshNor) {
  48852. this._normal.x = meshNor[n];
  48853. this._normal.y = meshNor[n + 1];
  48854. this._normal.z = meshNor[n + 2];
  48855. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  48856. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48857. n += 3;
  48858. }
  48859. }
  48860. for (i = 0; i < meshInd.length; i++) {
  48861. var current_ind = p + meshInd[i];
  48862. indices.push(current_ind);
  48863. if (current_ind > 65535) {
  48864. this._needs32Bits = true;
  48865. }
  48866. }
  48867. if (this._pickable) {
  48868. var nbfaces = meshInd.length / 3;
  48869. for (i = 0; i < nbfaces; i++) {
  48870. this.pickedParticles.push({ idx: idx, faceId: i });
  48871. }
  48872. }
  48873. if (this._depthSort) {
  48874. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  48875. }
  48876. return this._copy;
  48877. };
  48878. // returns a shape array from positions array
  48879. SolidParticleSystem.prototype._posToShape = function (positions) {
  48880. var shape = [];
  48881. for (var i = 0; i < positions.length; i += 3) {
  48882. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  48883. }
  48884. return shape;
  48885. };
  48886. // returns a shapeUV array from a Vector4 uvs
  48887. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  48888. var shapeUV = [];
  48889. if (uvs) {
  48890. for (var i = 0; i < uvs.length; i++)
  48891. shapeUV.push(uvs[i]);
  48892. }
  48893. return shapeUV;
  48894. };
  48895. // adds a new particle object in the particles array
  48896. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  48897. if (bInfo === void 0) { bInfo = null; }
  48898. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  48899. this.particles.push(sp);
  48900. return sp;
  48901. };
  48902. /**
  48903. * Adds some particles to the SPS from the model shape. Returns the shape id.
  48904. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  48905. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  48906. * @param nb (positive integer) the number of particles to be created from this model
  48907. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  48908. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  48909. * @returns the number of shapes in the system
  48910. */
  48911. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  48912. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48913. var meshInd = mesh.getIndices();
  48914. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48915. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48916. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48917. var bbInfo;
  48918. if (this._particlesIntersect) {
  48919. bbInfo = mesh.getBoundingInfo();
  48920. }
  48921. var shape = this._posToShape(meshPos);
  48922. var shapeUV = this._uvsToShapeUV(meshUV);
  48923. var posfunc = options ? options.positionFunction : null;
  48924. var vtxfunc = options ? options.vertexFunction : null;
  48925. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  48926. // particles
  48927. var sp;
  48928. var currentCopy;
  48929. var idx = this.nbParticles;
  48930. for (var i = 0; i < nb; i++) {
  48931. var currentPos = this._positions.length;
  48932. var currentInd = this._indices.length;
  48933. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  48934. if (this._updatable) {
  48935. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  48936. sp.position.copyFrom(currentCopy.position);
  48937. sp.rotation.copyFrom(currentCopy.rotation);
  48938. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  48939. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  48940. }
  48941. if (currentCopy.color && sp.color) {
  48942. sp.color.copyFrom(currentCopy.color);
  48943. }
  48944. sp.scaling.copyFrom(currentCopy.scaling);
  48945. sp.uvs.copyFrom(currentCopy.uvs);
  48946. }
  48947. this._index += shape.length;
  48948. idx++;
  48949. }
  48950. this.nbParticles += nb;
  48951. this._shapeCounter++;
  48952. return this._shapeCounter - 1;
  48953. };
  48954. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  48955. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  48956. this._resetCopy();
  48957. if (particle._model._positionFunction) {
  48958. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  48959. }
  48960. if (this._copy.rotationQuaternion) {
  48961. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48962. }
  48963. else {
  48964. this._yaw = this._copy.rotation.y;
  48965. this._pitch = this._copy.rotation.x;
  48966. this._roll = this._copy.rotation.z;
  48967. this._quaternionRotationYPR();
  48968. }
  48969. this._quaternionToRotationMatrix();
  48970. this._shape = particle._model._shape;
  48971. for (var pt = 0; pt < this._shape.length; pt++) {
  48972. this._vertex.x = this._shape[pt].x;
  48973. this._vertex.y = this._shape[pt].y;
  48974. this._vertex.z = this._shape[pt].z;
  48975. if (particle._model._vertexFunction) {
  48976. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48977. }
  48978. this._vertex.x *= this._copy.scaling.x;
  48979. this._vertex.y *= this._copy.scaling.y;
  48980. this._vertex.z *= this._copy.scaling.z;
  48981. this._vertex.x += this._copy.pivot.x;
  48982. this._vertex.y += this._copy.pivot.y;
  48983. this._vertex.z += this._copy.pivot.z;
  48984. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48985. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48986. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48987. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48988. }
  48989. particle.position.x = 0.0;
  48990. particle.position.y = 0.0;
  48991. particle.position.z = 0.0;
  48992. particle.rotation.x = 0.0;
  48993. particle.rotation.y = 0.0;
  48994. particle.rotation.z = 0.0;
  48995. particle.rotationQuaternion = null;
  48996. particle.scaling.x = 1.0;
  48997. particle.scaling.y = 1.0;
  48998. particle.scaling.z = 1.0;
  48999. };
  49000. /**
  49001. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49002. * @returns the SPS.
  49003. */
  49004. SolidParticleSystem.prototype.rebuildMesh = function () {
  49005. for (var p = 0; p < this.particles.length; p++) {
  49006. this._rebuildParticle(this.particles[p]);
  49007. }
  49008. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49009. return this;
  49010. };
  49011. /**
  49012. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49013. * This method calls `updateParticle()` for each particle of the SPS.
  49014. * For an animated SPS, it is usually called within the render loop.
  49015. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49016. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49017. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49018. * @returns the SPS.
  49019. */
  49020. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49021. if (start === void 0) { start = 0; }
  49022. if (end === void 0) { end = this.nbParticles - 1; }
  49023. if (update === void 0) { update = true; }
  49024. if (!this._updatable) {
  49025. return this;
  49026. }
  49027. // custom beforeUpdate
  49028. this.beforeUpdateParticles(start, end, update);
  49029. this._cam_axisX.x = 1.0;
  49030. this._cam_axisX.y = 0.0;
  49031. this._cam_axisX.z = 0.0;
  49032. this._cam_axisY.x = 0.0;
  49033. this._cam_axisY.y = 1.0;
  49034. this._cam_axisY.z = 0.0;
  49035. this._cam_axisZ.x = 0.0;
  49036. this._cam_axisZ.y = 0.0;
  49037. this._cam_axisZ.z = 1.0;
  49038. // cases when the World Matrix is to be computed first
  49039. if (this.billboard || this._depthSort) {
  49040. this.mesh.computeWorldMatrix(true);
  49041. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49042. }
  49043. // if the particles will always face the camera
  49044. if (this.billboard) {
  49045. // compute the camera position and un-rotate it by the current mesh rotation
  49046. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49047. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49048. this._cam_axisZ.normalize();
  49049. // same for camera up vector extracted from the cam view matrix
  49050. var view = this._camera.getViewMatrix(true);
  49051. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49052. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49053. this._cam_axisY.normalize();
  49054. this._cam_axisX.normalize();
  49055. }
  49056. // if depthSort, compute the camera global position in the mesh local system
  49057. if (this._depthSort) {
  49058. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49059. }
  49060. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49061. var idx = 0; // current position index in the global array positions32
  49062. var index = 0; // position start index in the global array positions32 of the current particle
  49063. var colidx = 0; // current color index in the global array colors32
  49064. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49065. var uvidx = 0; // current uv index in the global array uvs32
  49066. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49067. var pt = 0; // current index in the particle model shape
  49068. if (this.mesh.isFacetDataEnabled) {
  49069. this._computeBoundingBox = true;
  49070. }
  49071. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49072. if (this._computeBoundingBox) {
  49073. if (start == 0 && end == this.nbParticles - 1) {
  49074. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49075. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49076. }
  49077. else {
  49078. if (this.mesh._boundingInfo) {
  49079. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49080. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49081. }
  49082. }
  49083. }
  49084. // particle loop
  49085. index = this.particles[start]._pos;
  49086. var vpos = (index / 3) | 0;
  49087. colorIndex = vpos * 4;
  49088. uvIndex = vpos * 2;
  49089. for (var p = start; p <= end; p++) {
  49090. this._particle = this.particles[p];
  49091. this._shape = this._particle._model._shape;
  49092. this._shapeUV = this._particle._model._shapeUV;
  49093. // call to custom user function to update the particle properties
  49094. this.updateParticle(this._particle);
  49095. // camera-particle distance for depth sorting
  49096. if (this._depthSort && this._depthSortParticles) {
  49097. var dsp = this.depthSortedParticles[p];
  49098. dsp.ind = this._particle._ind;
  49099. dsp.indicesLength = this._particle._model._indicesLength;
  49100. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49101. }
  49102. // skip the computations for inactive or already invisible particles
  49103. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49104. // increment indexes for the next particle
  49105. pt = this._shape.length;
  49106. index += pt * 3;
  49107. colorIndex += pt * 4;
  49108. uvIndex += pt * 2;
  49109. continue;
  49110. }
  49111. if (this._particle.isVisible) {
  49112. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49113. // particle rotation matrix
  49114. if (this.billboard) {
  49115. this._particle.rotation.x = 0.0;
  49116. this._particle.rotation.y = 0.0;
  49117. }
  49118. if (this._computeParticleRotation || this.billboard) {
  49119. if (this._particle.rotationQuaternion) {
  49120. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49121. }
  49122. else {
  49123. this._yaw = this._particle.rotation.y;
  49124. this._pitch = this._particle.rotation.x;
  49125. this._roll = this._particle.rotation.z;
  49126. this._quaternionRotationYPR();
  49127. }
  49128. this._quaternionToRotationMatrix();
  49129. }
  49130. // particle vertex loop
  49131. for (pt = 0; pt < this._shape.length; pt++) {
  49132. idx = index + pt * 3;
  49133. colidx = colorIndex + pt * 4;
  49134. uvidx = uvIndex + pt * 2;
  49135. this._vertex.x = this._shape[pt].x;
  49136. this._vertex.y = this._shape[pt].y;
  49137. this._vertex.z = this._shape[pt].z;
  49138. if (this._computeParticleVertex) {
  49139. this.updateParticleVertex(this._particle, this._vertex, pt);
  49140. }
  49141. // positions
  49142. this._vertex.x *= this._particle.scaling.x;
  49143. this._vertex.y *= this._particle.scaling.y;
  49144. this._vertex.z *= this._particle.scaling.z;
  49145. this._vertex.x += this._particle.pivot.x;
  49146. this._vertex.y += this._particle.pivot.y;
  49147. this._vertex.z += this._particle.pivot.z;
  49148. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49149. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49150. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49151. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49152. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  49153. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  49154. if (this._computeBoundingBox) {
  49155. if (this._positions32[idx] < this._minimum.x) {
  49156. this._minimum.x = this._positions32[idx];
  49157. }
  49158. if (this._positions32[idx] > this._maximum.x) {
  49159. this._maximum.x = this._positions32[idx];
  49160. }
  49161. if (this._positions32[idx + 1] < this._minimum.y) {
  49162. this._minimum.y = this._positions32[idx + 1];
  49163. }
  49164. if (this._positions32[idx + 1] > this._maximum.y) {
  49165. this._maximum.y = this._positions32[idx + 1];
  49166. }
  49167. if (this._positions32[idx + 2] < this._minimum.z) {
  49168. this._minimum.z = this._positions32[idx + 2];
  49169. }
  49170. if (this._positions32[idx + 2] > this._maximum.z) {
  49171. this._maximum.z = this._positions32[idx + 2];
  49172. }
  49173. }
  49174. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49175. if (!this._computeParticleVertex) {
  49176. this._normal.x = this._fixedNormal32[idx];
  49177. this._normal.y = this._fixedNormal32[idx + 1];
  49178. this._normal.z = this._fixedNormal32[idx + 2];
  49179. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49180. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49181. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49182. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49183. 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;
  49184. 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;
  49185. }
  49186. if (this._computeParticleColor && this._particle.color) {
  49187. this._colors32[colidx] = this._particle.color.r;
  49188. this._colors32[colidx + 1] = this._particle.color.g;
  49189. this._colors32[colidx + 2] = this._particle.color.b;
  49190. this._colors32[colidx + 3] = this._particle.color.a;
  49191. }
  49192. if (this._computeParticleTexture) {
  49193. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49194. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49195. }
  49196. }
  49197. }
  49198. else {
  49199. this._particle._stillInvisible = true; // mark the particle as invisible
  49200. for (pt = 0; pt < this._shape.length; pt++) {
  49201. idx = index + pt * 3;
  49202. colidx = colorIndex + pt * 4;
  49203. uvidx = uvIndex + pt * 2;
  49204. this._positions32[idx] = 0.0;
  49205. this._positions32[idx + 1] = 0.0;
  49206. this._positions32[idx + 2] = 0.0;
  49207. this._normals32[idx] = 0.0;
  49208. this._normals32[idx + 1] = 0.0;
  49209. this._normals32[idx + 2] = 0.0;
  49210. if (this._computeParticleColor && this._particle.color) {
  49211. this._colors32[colidx] = this._particle.color.r;
  49212. this._colors32[colidx + 1] = this._particle.color.g;
  49213. this._colors32[colidx + 2] = this._particle.color.b;
  49214. this._colors32[colidx + 3] = this._particle.color.a;
  49215. }
  49216. if (this._computeParticleTexture) {
  49217. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49218. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49219. }
  49220. }
  49221. }
  49222. // if the particle intersections must be computed : update the bbInfo
  49223. if (this._particlesIntersect) {
  49224. var bInfo = this._particle._boundingInfo;
  49225. var bBox = bInfo.boundingBox;
  49226. var bSphere = bInfo.boundingSphere;
  49227. if (!this._bSphereOnly) {
  49228. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49229. for (var b = 0; b < bBox.vectors.length; b++) {
  49230. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49231. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49232. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49233. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49234. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49235. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49236. 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;
  49237. 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;
  49238. 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;
  49239. }
  49240. bBox._update(this.mesh._worldMatrix);
  49241. }
  49242. // place and scale the particle bouding sphere in the SPS local system, then update it
  49243. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49244. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49245. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49246. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49247. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49248. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49249. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49250. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49251. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49252. 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));
  49253. bSphere._update(this.mesh._worldMatrix);
  49254. }
  49255. // increment indexes for the next particle
  49256. index = idx + 3;
  49257. colorIndex = colidx + 4;
  49258. uvIndex = uvidx + 2;
  49259. }
  49260. // if the VBO must be updated
  49261. if (update) {
  49262. if (this._computeParticleColor) {
  49263. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49264. }
  49265. if (this._computeParticleTexture) {
  49266. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49267. }
  49268. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49269. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49270. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49271. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49272. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49273. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49274. for (var i = 0; i < this._normals32.length; i++) {
  49275. this._fixedNormal32[i] = this._normals32[i];
  49276. }
  49277. }
  49278. if (!this.mesh.areNormalsFrozen) {
  49279. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49280. }
  49281. }
  49282. if (this._depthSort && this._depthSortParticles) {
  49283. this.depthSortedParticles.sort(this._depthSortFunction);
  49284. var dspl = this.depthSortedParticles.length;
  49285. var sorted = 0;
  49286. var lind = 0;
  49287. var sind = 0;
  49288. var sid = 0;
  49289. for (sorted = 0; sorted < dspl; sorted++) {
  49290. lind = this.depthSortedParticles[sorted].indicesLength;
  49291. sind = this.depthSortedParticles[sorted].ind;
  49292. for (var i = 0; i < lind; i++) {
  49293. this._indices32[sid] = this._indices[sind + i];
  49294. sid++;
  49295. }
  49296. }
  49297. this.mesh.updateIndices(this._indices32);
  49298. }
  49299. }
  49300. if (this._computeBoundingBox) {
  49301. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49302. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49303. }
  49304. this.afterUpdateParticles(start, end, update);
  49305. return this;
  49306. };
  49307. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49308. this._halfroll = this._roll * 0.5;
  49309. this._halfpitch = this._pitch * 0.5;
  49310. this._halfyaw = this._yaw * 0.5;
  49311. this._sinRoll = Math.sin(this._halfroll);
  49312. this._cosRoll = Math.cos(this._halfroll);
  49313. this._sinPitch = Math.sin(this._halfpitch);
  49314. this._cosPitch = Math.cos(this._halfpitch);
  49315. this._sinYaw = Math.sin(this._halfyaw);
  49316. this._cosYaw = Math.cos(this._halfyaw);
  49317. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49318. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49319. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49320. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49321. };
  49322. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49323. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49324. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49325. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49326. this._rotMatrix.m[3] = 0;
  49327. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49328. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49329. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49330. this._rotMatrix.m[7] = 0;
  49331. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49332. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49333. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49334. this._rotMatrix.m[11] = 0;
  49335. this._rotMatrix.m[12] = 0;
  49336. this._rotMatrix.m[13] = 0;
  49337. this._rotMatrix.m[14] = 0;
  49338. this._rotMatrix.m[15] = 1.0;
  49339. };
  49340. /**
  49341. * Disposes the SPS.
  49342. */
  49343. SolidParticleSystem.prototype.dispose = function () {
  49344. this.mesh.dispose();
  49345. this.vars = null;
  49346. // drop references to internal big arrays for the GC
  49347. this._positions = null;
  49348. this._indices = null;
  49349. this._normals = null;
  49350. this._uvs = null;
  49351. this._colors = null;
  49352. this._indices32 = null;
  49353. this._positions32 = null;
  49354. this._normals32 = null;
  49355. this._fixedNormal32 = null;
  49356. this._uvs32 = null;
  49357. this._colors32 = null;
  49358. this.pickedParticles = null;
  49359. };
  49360. /**
  49361. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49362. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49363. * @returns the SPS.
  49364. */
  49365. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49366. if (!this._isVisibilityBoxLocked) {
  49367. this.mesh.refreshBoundingInfo();
  49368. }
  49369. return this;
  49370. };
  49371. /**
  49372. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49373. * @param size the size (float) of the visibility box
  49374. * note : this doesn't lock the SPS mesh bounding box.
  49375. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49376. */
  49377. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49378. var vis = size / 2;
  49379. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49380. };
  49381. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49382. /**
  49383. * Gets whether the SPS as always visible or not
  49384. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49385. */
  49386. get: function () {
  49387. return this._alwaysVisible;
  49388. },
  49389. /**
  49390. * Sets the SPS as always visible or not
  49391. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49392. */
  49393. set: function (val) {
  49394. this._alwaysVisible = val;
  49395. this.mesh.alwaysSelectAsActiveMesh = val;
  49396. },
  49397. enumerable: true,
  49398. configurable: true
  49399. });
  49400. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49401. /**
  49402. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49403. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49404. */
  49405. get: function () {
  49406. return this._isVisibilityBoxLocked;
  49407. },
  49408. /**
  49409. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49410. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49411. */
  49412. set: function (val) {
  49413. this._isVisibilityBoxLocked = val;
  49414. var boundingInfo = this.mesh.getBoundingInfo();
  49415. boundingInfo.isLocked = val;
  49416. },
  49417. enumerable: true,
  49418. configurable: true
  49419. });
  49420. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49421. /**
  49422. * Gets if `setParticles()` computes the particle rotations or not.
  49423. * Default value : true. The SPS is faster when it's set to false.
  49424. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49425. */
  49426. get: function () {
  49427. return this._computeParticleRotation;
  49428. },
  49429. /**
  49430. * Tells to `setParticles()` to compute the particle rotations or not.
  49431. * Default value : true. The SPS is faster when it's set to false.
  49432. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49433. */
  49434. set: function (val) {
  49435. this._computeParticleRotation = val;
  49436. },
  49437. enumerable: true,
  49438. configurable: true
  49439. });
  49440. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49441. /**
  49442. * Gets if `setParticles()` computes the particle colors or not.
  49443. * Default value : true. The SPS is faster when it's set to false.
  49444. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49445. */
  49446. get: function () {
  49447. return this._computeParticleColor;
  49448. },
  49449. /**
  49450. * Tells to `setParticles()` to compute the particle colors or not.
  49451. * Default value : true. The SPS is faster when it's set to false.
  49452. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49453. */
  49454. set: function (val) {
  49455. this._computeParticleColor = val;
  49456. },
  49457. enumerable: true,
  49458. configurable: true
  49459. });
  49460. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49461. /**
  49462. * Gets if `setParticles()` computes the particle textures or not.
  49463. * Default value : true. The SPS is faster when it's set to false.
  49464. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49465. */
  49466. get: function () {
  49467. return this._computeParticleTexture;
  49468. },
  49469. set: function (val) {
  49470. this._computeParticleTexture = val;
  49471. },
  49472. enumerable: true,
  49473. configurable: true
  49474. });
  49475. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49476. /**
  49477. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  49478. * Default value : false. The SPS is faster when it's set to false.
  49479. * Note : the particle custom vertex positions aren't stored values.
  49480. */
  49481. get: function () {
  49482. return this._computeParticleVertex;
  49483. },
  49484. /**
  49485. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49486. * Default value : false. The SPS is faster when it's set to false.
  49487. * Note : the particle custom vertex positions aren't stored values.
  49488. */
  49489. set: function (val) {
  49490. this._computeParticleVertex = val;
  49491. },
  49492. enumerable: true,
  49493. configurable: true
  49494. });
  49495. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49496. /**
  49497. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  49498. */
  49499. get: function () {
  49500. return this._computeBoundingBox;
  49501. },
  49502. /**
  49503. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49504. */
  49505. set: function (val) {
  49506. this._computeBoundingBox = val;
  49507. },
  49508. enumerable: true,
  49509. configurable: true
  49510. });
  49511. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  49512. /**
  49513. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  49514. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49515. * Default : `true`
  49516. */
  49517. get: function () {
  49518. return this._depthSortParticles;
  49519. },
  49520. /**
  49521. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  49522. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49523. * Default : `true`
  49524. */
  49525. set: function (val) {
  49526. this._depthSortParticles = val;
  49527. },
  49528. enumerable: true,
  49529. configurable: true
  49530. });
  49531. // =======================================================================
  49532. // Particle behavior logic
  49533. // these following methods may be overwritten by the user to fit his needs
  49534. /**
  49535. * This function does nothing. It may be overwritten to set all the particle first values.
  49536. * The SPS doesn't call this function, you may have to call it by your own.
  49537. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49538. */
  49539. SolidParticleSystem.prototype.initParticles = function () {
  49540. };
  49541. /**
  49542. * This function does nothing. It may be overwritten to recycle a particle.
  49543. * The SPS doesn't call this function, you may have to call it by your own.
  49544. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49545. * @param particle The particle to recycle
  49546. * @returns the recycled particle
  49547. */
  49548. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49549. return particle;
  49550. };
  49551. /**
  49552. * Updates a particle : this function should be overwritten by the user.
  49553. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49554. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49555. * @example : just set a particle position or velocity and recycle conditions
  49556. * @param particle The particle to update
  49557. * @returns the updated particle
  49558. */
  49559. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49560. return particle;
  49561. };
  49562. /**
  49563. * Updates a vertex of a particle : it can be overwritten by the user.
  49564. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49565. * @param particle the current particle
  49566. * @param vertex the current index of the current particle
  49567. * @param pt the index of the current vertex in the particle shape
  49568. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49569. * @example : just set a vertex particle position
  49570. * @returns the updated vertex
  49571. */
  49572. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49573. return vertex;
  49574. };
  49575. /**
  49576. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49577. * This does nothing and may be overwritten by the user.
  49578. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49579. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49580. * @param update the boolean update value actually passed to setParticles()
  49581. */
  49582. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49583. };
  49584. /**
  49585. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49586. * This will be passed three parameters.
  49587. * This does nothing and may be overwritten by the user.
  49588. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49589. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49590. * @param update the boolean update value actually passed to setParticles()
  49591. */
  49592. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49593. };
  49594. return SolidParticleSystem;
  49595. }());
  49596. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49597. })(BABYLON || (BABYLON = {}));
  49598. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49599. var BABYLON;
  49600. (function (BABYLON) {
  49601. var ShaderMaterial = /** @class */ (function (_super) {
  49602. __extends(ShaderMaterial, _super);
  49603. function ShaderMaterial(name, scene, shaderPath, options) {
  49604. var _this = _super.call(this, name, scene) || this;
  49605. _this._textures = {};
  49606. _this._textureArrays = {};
  49607. _this._floats = {};
  49608. _this._ints = {};
  49609. _this._floatsArrays = {};
  49610. _this._colors3 = {};
  49611. _this._colors3Arrays = {};
  49612. _this._colors4 = {};
  49613. _this._vectors2 = {};
  49614. _this._vectors3 = {};
  49615. _this._vectors4 = {};
  49616. _this._matrices = {};
  49617. _this._matrices3x3 = {};
  49618. _this._matrices2x2 = {};
  49619. _this._vectors2Arrays = {};
  49620. _this._vectors3Arrays = {};
  49621. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49622. _this._shaderPath = shaderPath;
  49623. options.needAlphaBlending = options.needAlphaBlending || false;
  49624. options.needAlphaTesting = options.needAlphaTesting || false;
  49625. options.attributes = options.attributes || ["position", "normal", "uv"];
  49626. options.uniforms = options.uniforms || ["worldViewProjection"];
  49627. options.uniformBuffers = options.uniformBuffers || [];
  49628. options.samplers = options.samplers || [];
  49629. options.defines = options.defines || [];
  49630. _this._options = options;
  49631. return _this;
  49632. }
  49633. ShaderMaterial.prototype.getClassName = function () {
  49634. return "ShaderMaterial";
  49635. };
  49636. ShaderMaterial.prototype.needAlphaBlending = function () {
  49637. return this._options.needAlphaBlending;
  49638. };
  49639. ShaderMaterial.prototype.needAlphaTesting = function () {
  49640. return this._options.needAlphaTesting;
  49641. };
  49642. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49643. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49644. this._options.uniforms.push(uniformName);
  49645. }
  49646. };
  49647. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49648. if (this._options.samplers.indexOf(name) === -1) {
  49649. this._options.samplers.push(name);
  49650. }
  49651. this._textures[name] = texture;
  49652. return this;
  49653. };
  49654. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49655. if (this._options.samplers.indexOf(name) === -1) {
  49656. this._options.samplers.push(name);
  49657. }
  49658. this._checkUniform(name);
  49659. this._textureArrays[name] = textures;
  49660. return this;
  49661. };
  49662. ShaderMaterial.prototype.setFloat = function (name, value) {
  49663. this._checkUniform(name);
  49664. this._floats[name] = value;
  49665. return this;
  49666. };
  49667. ShaderMaterial.prototype.setInt = function (name, value) {
  49668. this._checkUniform(name);
  49669. this._ints[name] = value;
  49670. return this;
  49671. };
  49672. ShaderMaterial.prototype.setFloats = function (name, value) {
  49673. this._checkUniform(name);
  49674. this._floatsArrays[name] = value;
  49675. return this;
  49676. };
  49677. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49678. this._checkUniform(name);
  49679. this._colors3[name] = value;
  49680. return this;
  49681. };
  49682. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  49683. this._checkUniform(name);
  49684. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  49685. color.toArray(arr, arr.length);
  49686. return arr;
  49687. }, []);
  49688. return this;
  49689. };
  49690. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49691. this._checkUniform(name);
  49692. this._colors4[name] = value;
  49693. return this;
  49694. };
  49695. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49696. this._checkUniform(name);
  49697. this._vectors2[name] = value;
  49698. return this;
  49699. };
  49700. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49701. this._checkUniform(name);
  49702. this._vectors3[name] = value;
  49703. return this;
  49704. };
  49705. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49706. this._checkUniform(name);
  49707. this._vectors4[name] = value;
  49708. return this;
  49709. };
  49710. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49711. this._checkUniform(name);
  49712. this._matrices[name] = value;
  49713. return this;
  49714. };
  49715. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49716. this._checkUniform(name);
  49717. this._matrices3x3[name] = value;
  49718. return this;
  49719. };
  49720. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49721. this._checkUniform(name);
  49722. this._matrices2x2[name] = value;
  49723. return this;
  49724. };
  49725. ShaderMaterial.prototype.setArray2 = function (name, value) {
  49726. this._checkUniform(name);
  49727. this._vectors2Arrays[name] = value;
  49728. return this;
  49729. };
  49730. ShaderMaterial.prototype.setArray3 = function (name, value) {
  49731. this._checkUniform(name);
  49732. this._vectors3Arrays[name] = value;
  49733. return this;
  49734. };
  49735. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  49736. if (!mesh) {
  49737. return true;
  49738. }
  49739. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  49740. return false;
  49741. }
  49742. return false;
  49743. };
  49744. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49745. var scene = this.getScene();
  49746. var engine = scene.getEngine();
  49747. if (!this.checkReadyOnEveryCall) {
  49748. if (this._renderId === scene.getRenderId()) {
  49749. if (this._checkCache(scene, mesh, useInstances)) {
  49750. return true;
  49751. }
  49752. }
  49753. }
  49754. // Instances
  49755. var defines = [];
  49756. var attribs = [];
  49757. var fallbacks = new BABYLON.EffectFallbacks();
  49758. if (useInstances) {
  49759. defines.push("#define INSTANCES");
  49760. }
  49761. for (var index = 0; index < this._options.defines.length; index++) {
  49762. defines.push(this._options.defines[index]);
  49763. }
  49764. for (var index = 0; index < this._options.attributes.length; index++) {
  49765. attribs.push(this._options.attributes[index]);
  49766. }
  49767. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  49768. attribs.push(BABYLON.VertexBuffer.ColorKind);
  49769. defines.push("#define VERTEXCOLOR");
  49770. }
  49771. // Bones
  49772. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  49773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49775. if (mesh.numBoneInfluencers > 4) {
  49776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49778. }
  49779. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49780. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49781. fallbacks.addCPUSkinningFallback(0, mesh);
  49782. if (this._options.uniforms.indexOf("mBones") === -1) {
  49783. this._options.uniforms.push("mBones");
  49784. }
  49785. }
  49786. else {
  49787. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49788. }
  49789. // Textures
  49790. for (var name in this._textures) {
  49791. if (!this._textures[name].isReady()) {
  49792. return false;
  49793. }
  49794. }
  49795. // Alpha test
  49796. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  49797. defines.push("#define ALPHATEST");
  49798. }
  49799. var previousEffect = this._effect;
  49800. var join = defines.join("\n");
  49801. this._effect = engine.createEffect(this._shaderPath, {
  49802. attributes: attribs,
  49803. uniformsNames: this._options.uniforms,
  49804. uniformBuffersNames: this._options.uniformBuffers,
  49805. samplers: this._options.samplers,
  49806. defines: join,
  49807. fallbacks: fallbacks,
  49808. onCompiled: this.onCompiled,
  49809. onError: this.onError
  49810. }, engine);
  49811. if (!this._effect.isReady()) {
  49812. return false;
  49813. }
  49814. if (previousEffect !== this._effect) {
  49815. scene.resetCachedMaterial();
  49816. }
  49817. this._renderId = scene.getRenderId();
  49818. return true;
  49819. };
  49820. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49821. var scene = this.getScene();
  49822. if (!this._effect) {
  49823. return;
  49824. }
  49825. if (this._options.uniforms.indexOf("world") !== -1) {
  49826. this._effect.setMatrix("world", world);
  49827. }
  49828. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49829. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49830. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49831. }
  49832. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49833. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49834. }
  49835. };
  49836. ShaderMaterial.prototype.bind = function (world, mesh) {
  49837. // Std values
  49838. this.bindOnlyWorldMatrix(world);
  49839. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  49840. if (this._options.uniforms.indexOf("view") !== -1) {
  49841. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49842. }
  49843. if (this._options.uniforms.indexOf("projection") !== -1) {
  49844. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49845. }
  49846. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49847. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49848. }
  49849. // Bones
  49850. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  49851. var name;
  49852. // Texture
  49853. for (name in this._textures) {
  49854. this._effect.setTexture(name, this._textures[name]);
  49855. }
  49856. // Texture arrays
  49857. for (name in this._textureArrays) {
  49858. this._effect.setTextureArray(name, this._textureArrays[name]);
  49859. }
  49860. // Int
  49861. for (name in this._ints) {
  49862. this._effect.setInt(name, this._ints[name]);
  49863. }
  49864. // Float
  49865. for (name in this._floats) {
  49866. this._effect.setFloat(name, this._floats[name]);
  49867. }
  49868. // Floats
  49869. for (name in this._floatsArrays) {
  49870. this._effect.setArray(name, this._floatsArrays[name]);
  49871. }
  49872. // Color3
  49873. for (name in this._colors3) {
  49874. this._effect.setColor3(name, this._colors3[name]);
  49875. }
  49876. for (name in this._colors3Arrays) {
  49877. this._effect.setArray3(name, this._colors3Arrays[name]);
  49878. }
  49879. // Color4
  49880. for (name in this._colors4) {
  49881. var color = this._colors4[name];
  49882. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49883. }
  49884. // Vector2
  49885. for (name in this._vectors2) {
  49886. this._effect.setVector2(name, this._vectors2[name]);
  49887. }
  49888. // Vector3
  49889. for (name in this._vectors3) {
  49890. this._effect.setVector3(name, this._vectors3[name]);
  49891. }
  49892. // Vector4
  49893. for (name in this._vectors4) {
  49894. this._effect.setVector4(name, this._vectors4[name]);
  49895. }
  49896. // Matrix
  49897. for (name in this._matrices) {
  49898. this._effect.setMatrix(name, this._matrices[name]);
  49899. }
  49900. // Matrix 3x3
  49901. for (name in this._matrices3x3) {
  49902. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49903. }
  49904. // Matrix 2x2
  49905. for (name in this._matrices2x2) {
  49906. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49907. }
  49908. // Vector2Array
  49909. for (name in this._vectors2Arrays) {
  49910. this._effect.setArray2(name, this._vectors2Arrays[name]);
  49911. }
  49912. // Vector3Array
  49913. for (name in this._vectors3Arrays) {
  49914. this._effect.setArray3(name, this._vectors3Arrays[name]);
  49915. }
  49916. }
  49917. this._afterBind(mesh);
  49918. };
  49919. ShaderMaterial.prototype.getActiveTextures = function () {
  49920. var activeTextures = _super.prototype.getActiveTextures.call(this);
  49921. for (var name in this._textures) {
  49922. activeTextures.push(this._textures[name]);
  49923. }
  49924. for (var name in this._textureArrays) {
  49925. var array = this._textureArrays[name];
  49926. for (var index = 0; index < array.length; index++) {
  49927. activeTextures.push(array[index]);
  49928. }
  49929. }
  49930. return activeTextures;
  49931. };
  49932. ShaderMaterial.prototype.hasTexture = function (texture) {
  49933. if (_super.prototype.hasTexture.call(this, texture)) {
  49934. return true;
  49935. }
  49936. for (var name in this._textures) {
  49937. if (this._textures[name] === texture) {
  49938. return true;
  49939. }
  49940. }
  49941. for (var name in this._textureArrays) {
  49942. var array = this._textureArrays[name];
  49943. for (var index = 0; index < array.length; index++) {
  49944. if (array[index] === texture) {
  49945. return true;
  49946. }
  49947. }
  49948. }
  49949. return false;
  49950. };
  49951. ShaderMaterial.prototype.clone = function (name) {
  49952. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49953. return newShaderMaterial;
  49954. };
  49955. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49956. if (forceDisposeTextures) {
  49957. var name;
  49958. for (name in this._textures) {
  49959. this._textures[name].dispose();
  49960. }
  49961. for (name in this._textureArrays) {
  49962. var array = this._textureArrays[name];
  49963. for (var index = 0; index < array.length; index++) {
  49964. array[index].dispose();
  49965. }
  49966. }
  49967. }
  49968. this._textures = {};
  49969. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49970. };
  49971. ShaderMaterial.prototype.serialize = function () {
  49972. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49973. serializationObject.customType = "BABYLON.ShaderMaterial";
  49974. serializationObject.options = this._options;
  49975. serializationObject.shaderPath = this._shaderPath;
  49976. var name;
  49977. // Texture
  49978. serializationObject.textures = {};
  49979. for (name in this._textures) {
  49980. serializationObject.textures[name] = this._textures[name].serialize();
  49981. }
  49982. // Texture arrays
  49983. serializationObject.textureArrays = {};
  49984. for (name in this._textureArrays) {
  49985. serializationObject.textureArrays[name] = [];
  49986. var array = this._textureArrays[name];
  49987. for (var index = 0; index < array.length; index++) {
  49988. serializationObject.textureArrays[name].push(array[index].serialize());
  49989. }
  49990. }
  49991. // Float
  49992. serializationObject.floats = {};
  49993. for (name in this._floats) {
  49994. serializationObject.floats[name] = this._floats[name];
  49995. }
  49996. // Float s
  49997. serializationObject.FloatArrays = {};
  49998. for (name in this._floatsArrays) {
  49999. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50000. }
  50001. // Color3
  50002. serializationObject.colors3 = {};
  50003. for (name in this._colors3) {
  50004. serializationObject.colors3[name] = this._colors3[name].asArray();
  50005. }
  50006. // Color3 array
  50007. serializationObject.colors3Arrays = {};
  50008. for (name in this._colors3Arrays) {
  50009. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50010. }
  50011. // Color4
  50012. serializationObject.colors4 = {};
  50013. for (name in this._colors4) {
  50014. serializationObject.colors4[name] = this._colors4[name].asArray();
  50015. }
  50016. // Vector2
  50017. serializationObject.vectors2 = {};
  50018. for (name in this._vectors2) {
  50019. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50020. }
  50021. // Vector3
  50022. serializationObject.vectors3 = {};
  50023. for (name in this._vectors3) {
  50024. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50025. }
  50026. // Vector4
  50027. serializationObject.vectors4 = {};
  50028. for (name in this._vectors4) {
  50029. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50030. }
  50031. // Matrix
  50032. serializationObject.matrices = {};
  50033. for (name in this._matrices) {
  50034. serializationObject.matrices[name] = this._matrices[name].asArray();
  50035. }
  50036. // Matrix 3x3
  50037. serializationObject.matrices3x3 = {};
  50038. for (name in this._matrices3x3) {
  50039. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50040. }
  50041. // Matrix 2x2
  50042. serializationObject.matrices2x2 = {};
  50043. for (name in this._matrices2x2) {
  50044. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50045. }
  50046. // Vector2Array
  50047. serializationObject.vectors2Arrays = {};
  50048. for (name in this._vectors2Arrays) {
  50049. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50050. }
  50051. // Vector3Array
  50052. serializationObject.vectors3Arrays = {};
  50053. for (name in this._vectors3Arrays) {
  50054. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50055. }
  50056. return serializationObject;
  50057. };
  50058. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50059. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50060. var name;
  50061. // Texture
  50062. for (name in source.textures) {
  50063. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50064. }
  50065. // Texture arrays
  50066. for (name in source.textureArrays) {
  50067. var array = source.textureArrays[name];
  50068. var textureArray = new Array();
  50069. for (var index = 0; index < array.length; index++) {
  50070. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50071. }
  50072. material.setTextureArray(name, textureArray);
  50073. }
  50074. // Float
  50075. for (name in source.floats) {
  50076. material.setFloat(name, source.floats[name]);
  50077. }
  50078. // Float s
  50079. for (name in source.floatsArrays) {
  50080. material.setFloats(name, source.floatsArrays[name]);
  50081. }
  50082. // Color3
  50083. for (name in source.colors3) {
  50084. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50085. }
  50086. // Color3 arrays
  50087. for (name in source.colors3Arrays) {
  50088. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50089. if (i % 3 === 0) {
  50090. arr.push([num]);
  50091. }
  50092. else {
  50093. arr[arr.length - 1].push(num);
  50094. }
  50095. return arr;
  50096. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50097. material.setColor3Array(name, colors);
  50098. }
  50099. // Color4
  50100. for (name in source.colors4) {
  50101. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50102. }
  50103. // Vector2
  50104. for (name in source.vectors2) {
  50105. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50106. }
  50107. // Vector3
  50108. for (name in source.vectors3) {
  50109. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50110. }
  50111. // Vector4
  50112. for (name in source.vectors4) {
  50113. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50114. }
  50115. // Matrix
  50116. for (name in source.matrices) {
  50117. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50118. }
  50119. // Matrix 3x3
  50120. for (name in source.matrices3x3) {
  50121. material.setMatrix3x3(name, source.matrices3x3[name]);
  50122. }
  50123. // Matrix 2x2
  50124. for (name in source.matrices2x2) {
  50125. material.setMatrix2x2(name, source.matrices2x2[name]);
  50126. }
  50127. // Vector2Array
  50128. for (name in source.vectors2Arrays) {
  50129. material.setArray2(name, source.vectors2Arrays[name]);
  50130. }
  50131. // Vector3Array
  50132. for (name in source.vectors3Arrays) {
  50133. material.setArray3(name, source.vectors3Arrays[name]);
  50134. }
  50135. return material;
  50136. };
  50137. return ShaderMaterial;
  50138. }(BABYLON.Material));
  50139. BABYLON.ShaderMaterial = ShaderMaterial;
  50140. })(BABYLON || (BABYLON = {}));
  50141. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50142. var BABYLON;
  50143. (function (BABYLON) {
  50144. var GroundMesh = /** @class */ (function (_super) {
  50145. __extends(GroundMesh, _super);
  50146. function GroundMesh(name, scene) {
  50147. var _this = _super.call(this, name, scene) || this;
  50148. _this.generateOctree = false;
  50149. return _this;
  50150. }
  50151. GroundMesh.prototype.getClassName = function () {
  50152. return "GroundMesh";
  50153. };
  50154. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50155. get: function () {
  50156. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50162. get: function () {
  50163. return this._subdivisionsX;
  50164. },
  50165. enumerable: true,
  50166. configurable: true
  50167. });
  50168. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50169. get: function () {
  50170. return this._subdivisionsY;
  50171. },
  50172. enumerable: true,
  50173. configurable: true
  50174. });
  50175. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50176. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50177. this._subdivisionsX = chunksCount;
  50178. this._subdivisionsY = chunksCount;
  50179. this.subdivide(chunksCount);
  50180. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50181. };
  50182. /**
  50183. * Returns a height (y) value in the Worl system :
  50184. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50185. * Returns the ground y position if (x, z) are outside the ground surface.
  50186. */
  50187. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50188. var world = this.getWorldMatrix();
  50189. var invMat = BABYLON.Tmp.Matrix[5];
  50190. world.invertToRef(invMat);
  50191. var tmpVect = BABYLON.Tmp.Vector3[8];
  50192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50193. x = tmpVect.x;
  50194. z = tmpVect.z;
  50195. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50196. return this.position.y;
  50197. }
  50198. if (!this._heightQuads || this._heightQuads.length == 0) {
  50199. this._initHeightQuads();
  50200. this._computeHeightQuads();
  50201. }
  50202. var facet = this._getFacetAt(x, z);
  50203. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50204. // return y in the World system
  50205. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50206. return tmpVect.y;
  50207. };
  50208. /**
  50209. * Returns a normalized vector (Vector3) orthogonal to the ground
  50210. * at the ground coordinates (x, z) expressed in the World system.
  50211. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50212. */
  50213. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50214. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50215. this.getNormalAtCoordinatesToRef(x, z, normal);
  50216. return normal;
  50217. };
  50218. /**
  50219. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50220. * at the ground coordinates (x, z) expressed in the World system.
  50221. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50222. * Returns the GroundMesh.
  50223. */
  50224. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50225. var world = this.getWorldMatrix();
  50226. var tmpMat = BABYLON.Tmp.Matrix[5];
  50227. world.invertToRef(tmpMat);
  50228. var tmpVect = BABYLON.Tmp.Vector3[8];
  50229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50230. x = tmpVect.x;
  50231. z = tmpVect.z;
  50232. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50233. return this;
  50234. }
  50235. if (!this._heightQuads || this._heightQuads.length == 0) {
  50236. this._initHeightQuads();
  50237. this._computeHeightQuads();
  50238. }
  50239. var facet = this._getFacetAt(x, z);
  50240. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50241. return this;
  50242. };
  50243. /**
  50244. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50245. * if the ground has been updated.
  50246. * This can be used in the render loop.
  50247. * Returns the GroundMesh.
  50248. */
  50249. GroundMesh.prototype.updateCoordinateHeights = function () {
  50250. if (!this._heightQuads || this._heightQuads.length == 0) {
  50251. this._initHeightQuads();
  50252. }
  50253. this._computeHeightQuads();
  50254. return this;
  50255. };
  50256. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50257. GroundMesh.prototype._getFacetAt = function (x, z) {
  50258. // retrieve col and row from x, z coordinates in the ground local system
  50259. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50260. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50261. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50262. var facet;
  50263. if (z < quad.slope.x * x + quad.slope.y) {
  50264. facet = quad.facet1;
  50265. }
  50266. else {
  50267. facet = quad.facet2;
  50268. }
  50269. return facet;
  50270. };
  50271. // Creates and populates the heightMap array with "facet" elements :
  50272. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50273. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50274. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50275. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50276. // Returns the GroundMesh.
  50277. GroundMesh.prototype._initHeightQuads = function () {
  50278. var subdivisionsX = this._subdivisionsX;
  50279. var subdivisionsY = this._subdivisionsY;
  50280. this._heightQuads = new Array();
  50281. for (var row = 0; row < subdivisionsY; row++) {
  50282. for (var col = 0; col < subdivisionsX; col++) {
  50283. 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) };
  50284. this._heightQuads[row * subdivisionsX + col] = quad;
  50285. }
  50286. }
  50287. return this;
  50288. };
  50289. // Compute each quad element values and update the the heightMap array :
  50290. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50291. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50292. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50293. // Returns the GroundMesh.
  50294. GroundMesh.prototype._computeHeightQuads = function () {
  50295. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50296. if (!positions) {
  50297. return this;
  50298. }
  50299. var v1 = BABYLON.Tmp.Vector3[3];
  50300. var v2 = BABYLON.Tmp.Vector3[2];
  50301. var v3 = BABYLON.Tmp.Vector3[1];
  50302. var v4 = BABYLON.Tmp.Vector3[0];
  50303. var v1v2 = BABYLON.Tmp.Vector3[4];
  50304. var v1v3 = BABYLON.Tmp.Vector3[5];
  50305. var v1v4 = BABYLON.Tmp.Vector3[6];
  50306. var norm1 = BABYLON.Tmp.Vector3[7];
  50307. var norm2 = BABYLON.Tmp.Vector3[8];
  50308. var i = 0;
  50309. var j = 0;
  50310. var k = 0;
  50311. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50312. var h = 0;
  50313. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50314. var d2 = 0;
  50315. var subdivisionsX = this._subdivisionsX;
  50316. var subdivisionsY = this._subdivisionsY;
  50317. for (var row = 0; row < subdivisionsY; row++) {
  50318. for (var col = 0; col < subdivisionsX; col++) {
  50319. i = col * 3;
  50320. j = row * (subdivisionsX + 1) * 3;
  50321. k = (row + 1) * (subdivisionsX + 1) * 3;
  50322. v1.x = positions[j + i];
  50323. v1.y = positions[j + i + 1];
  50324. v1.z = positions[j + i + 2];
  50325. v2.x = positions[j + i + 3];
  50326. v2.y = positions[j + i + 4];
  50327. v2.z = positions[j + i + 5];
  50328. v3.x = positions[k + i];
  50329. v3.y = positions[k + i + 1];
  50330. v3.z = positions[k + i + 2];
  50331. v4.x = positions[k + i + 3];
  50332. v4.y = positions[k + i + 4];
  50333. v4.z = positions[k + i + 5];
  50334. // 2D slope V1V4
  50335. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50336. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50337. // facet equations :
  50338. // we compute each facet normal vector
  50339. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50340. // we compute the value d by applying the equation to v1 which belongs to the plane
  50341. // then we store the facet equation in a Vector4
  50342. v2.subtractToRef(v1, v1v2);
  50343. v3.subtractToRef(v1, v1v3);
  50344. v4.subtractToRef(v1, v1v4);
  50345. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50346. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50347. norm1.normalize();
  50348. norm2.normalize();
  50349. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50350. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50351. var quad = this._heightQuads[row * subdivisionsX + col];
  50352. quad.slope.copyFromFloats(cd, h);
  50353. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50354. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50355. }
  50356. }
  50357. return this;
  50358. };
  50359. GroundMesh.prototype.serialize = function (serializationObject) {
  50360. _super.prototype.serialize.call(this, serializationObject);
  50361. serializationObject.subdivisionsX = this._subdivisionsX;
  50362. serializationObject.subdivisionsY = this._subdivisionsY;
  50363. serializationObject.minX = this._minX;
  50364. serializationObject.maxX = this._maxX;
  50365. serializationObject.minZ = this._minZ;
  50366. serializationObject.maxZ = this._maxZ;
  50367. serializationObject.width = this._width;
  50368. serializationObject.height = this._height;
  50369. };
  50370. GroundMesh.Parse = function (parsedMesh, scene) {
  50371. var result = new GroundMesh(parsedMesh.name, scene);
  50372. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50373. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50374. result._minX = parsedMesh.minX;
  50375. result._maxX = parsedMesh.maxX;
  50376. result._minZ = parsedMesh.minZ;
  50377. result._maxZ = parsedMesh.maxZ;
  50378. result._width = parsedMesh.width;
  50379. result._height = parsedMesh.height;
  50380. return result;
  50381. };
  50382. return GroundMesh;
  50383. }(BABYLON.Mesh));
  50384. BABYLON.GroundMesh = GroundMesh;
  50385. })(BABYLON || (BABYLON = {}));
  50386. //# sourceMappingURL=babylon.groundMesh.js.map
  50387. var BABYLON;
  50388. (function (BABYLON) {
  50389. /**
  50390. * Creates an instance based on a source mesh.
  50391. */
  50392. var InstancedMesh = /** @class */ (function (_super) {
  50393. __extends(InstancedMesh, _super);
  50394. function InstancedMesh(name, source) {
  50395. var _this = _super.call(this, name, source.getScene()) || this;
  50396. source.instances.push(_this);
  50397. _this._sourceMesh = source;
  50398. _this.position.copyFrom(source.position);
  50399. _this.rotation.copyFrom(source.rotation);
  50400. _this.scaling.copyFrom(source.scaling);
  50401. if (source.rotationQuaternion) {
  50402. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50403. }
  50404. _this.infiniteDistance = source.infiniteDistance;
  50405. _this.setPivotMatrix(source.getPivotMatrix());
  50406. _this.refreshBoundingInfo();
  50407. _this._syncSubMeshes();
  50408. return _this;
  50409. }
  50410. /**
  50411. * Returns the string "InstancedMesh".
  50412. */
  50413. InstancedMesh.prototype.getClassName = function () {
  50414. return "InstancedMesh";
  50415. };
  50416. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50417. // Methods
  50418. get: function () {
  50419. return this._sourceMesh.receiveShadows;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(InstancedMesh.prototype, "material", {
  50425. get: function () {
  50426. return this._sourceMesh.material;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50432. get: function () {
  50433. return this._sourceMesh.visibility;
  50434. },
  50435. enumerable: true,
  50436. configurable: true
  50437. });
  50438. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50439. get: function () {
  50440. return this._sourceMesh.skeleton;
  50441. },
  50442. enumerable: true,
  50443. configurable: true
  50444. });
  50445. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50446. get: function () {
  50447. return this._sourceMesh.renderingGroupId;
  50448. },
  50449. enumerable: true,
  50450. configurable: true
  50451. });
  50452. /**
  50453. * Returns the total number of vertices (integer).
  50454. */
  50455. InstancedMesh.prototype.getTotalVertices = function () {
  50456. return this._sourceMesh.getTotalVertices();
  50457. };
  50458. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50459. get: function () {
  50460. return this._sourceMesh;
  50461. },
  50462. enumerable: true,
  50463. configurable: true
  50464. });
  50465. /**
  50466. * Is this node ready to be used/rendered
  50467. * @return {boolean} is it ready
  50468. */
  50469. InstancedMesh.prototype.isReady = function () {
  50470. return this._sourceMesh.isReady(true);
  50471. };
  50472. /**
  50473. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  50474. */
  50475. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  50476. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  50477. };
  50478. /**
  50479. * Sets the vertex data of the mesh geometry for the requested `kind`.
  50480. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  50481. * The `data` are either a numeric array either a Float32Array.
  50482. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  50483. * 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).
  50484. * Note that a new underlying VertexBuffer object is created each call.
  50485. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  50486. *
  50487. * Possible `kind` values :
  50488. * - BABYLON.VertexBuffer.PositionKind
  50489. * - BABYLON.VertexBuffer.UVKind
  50490. * - BABYLON.VertexBuffer.UV2Kind
  50491. * - BABYLON.VertexBuffer.UV3Kind
  50492. * - BABYLON.VertexBuffer.UV4Kind
  50493. * - BABYLON.VertexBuffer.UV5Kind
  50494. * - BABYLON.VertexBuffer.UV6Kind
  50495. * - BABYLON.VertexBuffer.ColorKind
  50496. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50497. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50498. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50499. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50500. *
  50501. * Returns the Mesh.
  50502. */
  50503. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  50504. if (this.sourceMesh) {
  50505. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  50506. }
  50507. return this.sourceMesh;
  50508. };
  50509. /**
  50510. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  50511. * If the mesh has no geometry, it is simply returned as it is.
  50512. * The `data` are either a numeric array either a Float32Array.
  50513. * No new underlying VertexBuffer object is created.
  50514. * 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.
  50515. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  50516. *
  50517. * Possible `kind` values :
  50518. * - BABYLON.VertexBuffer.PositionKind
  50519. * - BABYLON.VertexBuffer.UVKind
  50520. * - BABYLON.VertexBuffer.UV2Kind
  50521. * - BABYLON.VertexBuffer.UV3Kind
  50522. * - BABYLON.VertexBuffer.UV4Kind
  50523. * - BABYLON.VertexBuffer.UV5Kind
  50524. * - BABYLON.VertexBuffer.UV6Kind
  50525. * - BABYLON.VertexBuffer.ColorKind
  50526. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50527. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50528. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50529. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50530. *
  50531. * Returns the Mesh.
  50532. */
  50533. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  50534. if (this.sourceMesh) {
  50535. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  50536. }
  50537. return this.sourceMesh;
  50538. };
  50539. /**
  50540. * Sets the mesh indices.
  50541. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  50542. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  50543. * This method creates a new index buffer each call.
  50544. * Returns the Mesh.
  50545. */
  50546. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  50547. if (totalVertices === void 0) { totalVertices = null; }
  50548. if (this.sourceMesh) {
  50549. this.sourceMesh.setIndices(indices, totalVertices);
  50550. }
  50551. return this.sourceMesh;
  50552. };
  50553. /**
  50554. * Boolean : True if the mesh owns the requested kind of data.
  50555. */
  50556. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  50557. return this._sourceMesh.isVerticesDataPresent(kind);
  50558. };
  50559. /**
  50560. * Returns an array of indices (IndicesArray).
  50561. */
  50562. InstancedMesh.prototype.getIndices = function () {
  50563. return this._sourceMesh.getIndices();
  50564. };
  50565. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  50566. get: function () {
  50567. return this._sourceMesh._positions;
  50568. },
  50569. enumerable: true,
  50570. configurable: true
  50571. });
  50572. /**
  50573. * Sets a new updated BoundingInfo to the mesh.
  50574. * Returns the mesh.
  50575. */
  50576. InstancedMesh.prototype.refreshBoundingInfo = function () {
  50577. var meshBB = this._sourceMesh.getBoundingInfo();
  50578. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  50579. this._updateBoundingInfo();
  50580. return this;
  50581. };
  50582. InstancedMesh.prototype._preActivate = function () {
  50583. if (this._currentLOD) {
  50584. this._currentLOD._preActivate();
  50585. }
  50586. return this;
  50587. };
  50588. InstancedMesh.prototype._activate = function (renderId) {
  50589. if (this._currentLOD) {
  50590. this._currentLOD._registerInstanceForRenderId(this, renderId);
  50591. }
  50592. return this;
  50593. };
  50594. /**
  50595. * Returns the current associated LOD AbstractMesh.
  50596. */
  50597. InstancedMesh.prototype.getLOD = function (camera) {
  50598. if (!camera) {
  50599. return this;
  50600. }
  50601. var boundingInfo = this.getBoundingInfo();
  50602. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  50603. if (this._currentLOD === this.sourceMesh) {
  50604. return this;
  50605. }
  50606. return this._currentLOD;
  50607. };
  50608. InstancedMesh.prototype._syncSubMeshes = function () {
  50609. this.releaseSubMeshes();
  50610. if (this._sourceMesh.subMeshes) {
  50611. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  50612. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  50613. }
  50614. }
  50615. return this;
  50616. };
  50617. InstancedMesh.prototype._generatePointsArray = function () {
  50618. return this._sourceMesh._generatePointsArray();
  50619. };
  50620. /**
  50621. * Creates a new InstancedMesh from the current mesh.
  50622. * - name (string) : the cloned mesh name
  50623. * - newParent (optional Node) : the optional Node to parent the clone to.
  50624. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  50625. *
  50626. * Returns the clone.
  50627. */
  50628. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50629. var result = this._sourceMesh.createInstance(name);
  50630. // Deep copy
  50631. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  50632. // Bounding info
  50633. this.refreshBoundingInfo();
  50634. // Parent
  50635. if (newParent) {
  50636. result.parent = newParent;
  50637. }
  50638. if (!doNotCloneChildren) {
  50639. // Children
  50640. for (var index = 0; index < this.getScene().meshes.length; index++) {
  50641. var mesh = this.getScene().meshes[index];
  50642. if (mesh.parent === this) {
  50643. mesh.clone(mesh.name, result);
  50644. }
  50645. }
  50646. }
  50647. result.computeWorldMatrix(true);
  50648. return result;
  50649. };
  50650. /**
  50651. * Disposes the InstancedMesh.
  50652. * Returns nothing.
  50653. */
  50654. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  50655. // Remove from mesh
  50656. var index = this._sourceMesh.instances.indexOf(this);
  50657. this._sourceMesh.instances.splice(index, 1);
  50658. _super.prototype.dispose.call(this, doNotRecurse);
  50659. };
  50660. return InstancedMesh;
  50661. }(BABYLON.AbstractMesh));
  50662. BABYLON.InstancedMesh = InstancedMesh;
  50663. })(BABYLON || (BABYLON = {}));
  50664. //# sourceMappingURL=babylon.instancedMesh.js.map
  50665. var BABYLON;
  50666. (function (BABYLON) {
  50667. var LinesMesh = /** @class */ (function (_super) {
  50668. __extends(LinesMesh, _super);
  50669. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  50670. if (scene === void 0) { scene = null; }
  50671. if (parent === void 0) { parent = null; }
  50672. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  50673. _this.useVertexColor = useVertexColor;
  50674. _this.useVertexAlpha = useVertexAlpha;
  50675. _this.color = new BABYLON.Color3(1, 1, 1);
  50676. _this.alpha = 1;
  50677. if (source) {
  50678. _this.color = source.color.clone();
  50679. _this.alpha = source.alpha;
  50680. _this.useVertexColor = source.useVertexColor;
  50681. _this.useVertexAlpha = source.useVertexAlpha;
  50682. }
  50683. _this._intersectionThreshold = 0.1;
  50684. var defines = [];
  50685. var options = {
  50686. attributes: [BABYLON.VertexBuffer.PositionKind],
  50687. uniforms: ["world", "viewProjection"],
  50688. needAlphaBlending: true,
  50689. defines: defines
  50690. };
  50691. if (useVertexAlpha === false) {
  50692. options.needAlphaBlending = false;
  50693. }
  50694. if (!useVertexColor) {
  50695. options.uniforms.push("color");
  50696. }
  50697. else {
  50698. options.defines.push("#define VERTEXCOLOR");
  50699. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  50700. }
  50701. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  50702. return _this;
  50703. }
  50704. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  50705. /**
  50706. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50707. * This margin is expressed in world space coordinates, so its value may vary.
  50708. * Default value is 0.1
  50709. * @returns the intersection Threshold value.
  50710. */
  50711. get: function () {
  50712. return this._intersectionThreshold;
  50713. },
  50714. /**
  50715. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50716. * This margin is expressed in world space coordinates, so its value may vary.
  50717. * @param value the new threshold to apply
  50718. */
  50719. set: function (value) {
  50720. if (this._intersectionThreshold === value) {
  50721. return;
  50722. }
  50723. this._intersectionThreshold = value;
  50724. if (this.geometry) {
  50725. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  50726. }
  50727. },
  50728. enumerable: true,
  50729. configurable: true
  50730. });
  50731. /**
  50732. * Returns the string "LineMesh"
  50733. */
  50734. LinesMesh.prototype.getClassName = function () {
  50735. return "LinesMesh";
  50736. };
  50737. Object.defineProperty(LinesMesh.prototype, "material", {
  50738. get: function () {
  50739. return this._colorShader;
  50740. },
  50741. set: function (value) {
  50742. // Do nothing
  50743. },
  50744. enumerable: true,
  50745. configurable: true
  50746. });
  50747. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  50748. get: function () {
  50749. return false;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. LinesMesh.prototype.createInstance = function (name) {
  50755. throw new Error("LinesMeshes do not support createInstance.");
  50756. };
  50757. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  50758. if (!this._geometry) {
  50759. return this;
  50760. }
  50761. // VBOs
  50762. this._geometry._bind(this._colorShader.getEffect());
  50763. // Color
  50764. if (!this.useVertexColor) {
  50765. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  50766. }
  50767. return this;
  50768. };
  50769. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  50770. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  50771. return this;
  50772. }
  50773. var engine = this.getScene().getEngine();
  50774. // Draw order
  50775. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  50776. return this;
  50777. };
  50778. LinesMesh.prototype.dispose = function (doNotRecurse) {
  50779. this._colorShader.dispose();
  50780. _super.prototype.dispose.call(this, doNotRecurse);
  50781. };
  50782. /**
  50783. * Returns a new LineMesh object cloned from the current one.
  50784. */
  50785. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50786. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  50787. };
  50788. return LinesMesh;
  50789. }(BABYLON.Mesh));
  50790. BABYLON.LinesMesh = LinesMesh;
  50791. })(BABYLON || (BABYLON = {}));
  50792. //# sourceMappingURL=babylon.linesMesh.js.map
  50793. var BABYLON;
  50794. (function (BABYLON) {
  50795. var MeshBuilder = /** @class */ (function () {
  50796. function MeshBuilder() {
  50797. }
  50798. MeshBuilder.updateSideOrientation = function (orientation) {
  50799. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  50800. return BABYLON.Mesh.DOUBLESIDE;
  50801. }
  50802. if (orientation === undefined || orientation === null) {
  50803. return BABYLON.Mesh.FRONTSIDE;
  50804. }
  50805. return orientation;
  50806. };
  50807. /**
  50808. * Creates a box mesh.
  50809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  50810. * The parameter `size` sets the size (float) of each box side (default 1).
  50811. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  50812. * 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).
  50813. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50814. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50815. * 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).
  50816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50818. */
  50819. MeshBuilder.CreateBox = function (name, options, scene) {
  50820. if (scene === void 0) { scene = null; }
  50821. var box = new BABYLON.Mesh(name, scene);
  50822. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50823. box._originalBuilderSideOrientation = options.sideOrientation;
  50824. var vertexData = BABYLON.VertexData.CreateBox(options);
  50825. vertexData.applyToMesh(box, options.updatable);
  50826. return box;
  50827. };
  50828. /**
  50829. * Creates a sphere mesh.
  50830. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  50831. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  50832. * 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`).
  50833. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  50834. * 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
  50835. * 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).
  50836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50837. * 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).
  50838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50840. */
  50841. MeshBuilder.CreateSphere = function (name, options, scene) {
  50842. var sphere = new BABYLON.Mesh(name, scene);
  50843. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50844. sphere._originalBuilderSideOrientation = options.sideOrientation;
  50845. var vertexData = BABYLON.VertexData.CreateSphere(options);
  50846. vertexData.applyToMesh(sphere, options.updatable);
  50847. return sphere;
  50848. };
  50849. /**
  50850. * Creates a plane polygonal mesh. By default, this is a disc.
  50851. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  50852. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  50853. * 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.
  50854. * 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
  50855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50856. * 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).
  50857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50859. */
  50860. MeshBuilder.CreateDisc = function (name, options, scene) {
  50861. if (scene === void 0) { scene = null; }
  50862. var disc = new BABYLON.Mesh(name, scene);
  50863. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50864. disc._originalBuilderSideOrientation = options.sideOrientation;
  50865. var vertexData = BABYLON.VertexData.CreateDisc(options);
  50866. vertexData.applyToMesh(disc, options.updatable);
  50867. return disc;
  50868. };
  50869. /**
  50870. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  50871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  50872. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  50873. * 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`).
  50874. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  50875. * 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.
  50876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50877. * 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).
  50878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50880. */
  50881. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  50882. var sphere = new BABYLON.Mesh(name, scene);
  50883. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50884. sphere._originalBuilderSideOrientation = options.sideOrientation;
  50885. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  50886. vertexData.applyToMesh(sphere, options.updatable);
  50887. return sphere;
  50888. };
  50889. ;
  50890. /**
  50891. * Creates a ribbon mesh.
  50892. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  50893. *
  50894. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  50895. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  50896. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  50897. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  50898. * 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.
  50899. * 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.
  50900. * 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
  50901. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50902. * 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).
  50903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50904. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50905. * 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.
  50906. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  50907. * 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
  50908. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  50909. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  50910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50911. */
  50912. MeshBuilder.CreateRibbon = function (name, options, scene) {
  50913. if (scene === void 0) { scene = null; }
  50914. var pathArray = options.pathArray;
  50915. var closeArray = options.closeArray;
  50916. var closePath = options.closePath;
  50917. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50918. var instance = options.instance;
  50919. var updatable = options.updatable;
  50920. if (instance) {
  50921. // positionFunction : ribbon case
  50922. // only pathArray and sideOrientation parameters are taken into account for positions update
  50923. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  50924. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  50925. var positionFunction = function (positions) {
  50926. var minlg = pathArray[0].length;
  50927. var i = 0;
  50928. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  50929. for (var si = 1; si <= ns; si++) {
  50930. for (var p = 0; p < pathArray.length; p++) {
  50931. var path = pathArray[p];
  50932. var l = path.length;
  50933. minlg = (minlg < l) ? minlg : l;
  50934. var j = 0;
  50935. while (j < minlg) {
  50936. positions[i] = path[j].x;
  50937. positions[i + 1] = path[j].y;
  50938. positions[i + 2] = path[j].z;
  50939. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  50940. BABYLON.Tmp.Vector3[0].x = path[j].x;
  50941. }
  50942. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  50943. BABYLON.Tmp.Vector3[1].x = path[j].x;
  50944. }
  50945. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  50946. BABYLON.Tmp.Vector3[0].y = path[j].y;
  50947. }
  50948. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  50949. BABYLON.Tmp.Vector3[1].y = path[j].y;
  50950. }
  50951. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  50952. BABYLON.Tmp.Vector3[0].z = path[j].z;
  50953. }
  50954. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  50955. BABYLON.Tmp.Vector3[1].z = path[j].z;
  50956. }
  50957. j++;
  50958. i += 3;
  50959. }
  50960. if (instance._closePath) {
  50961. positions[i] = path[0].x;
  50962. positions[i + 1] = path[0].y;
  50963. positions[i + 2] = path[0].z;
  50964. i += 3;
  50965. }
  50966. }
  50967. }
  50968. };
  50969. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50970. positionFunction(positions);
  50971. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  50972. instance._boundingInfo.update(instance._worldMatrix);
  50973. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  50974. if (options.colors) {
  50975. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50976. for (var c = 0; c < options.colors.length; c++) {
  50977. colors[c * 4] = options.colors[c].r;
  50978. colors[c * 4 + 1] = options.colors[c].g;
  50979. colors[c * 4 + 2] = options.colors[c].b;
  50980. colors[c * 4 + 3] = options.colors[c].a;
  50981. }
  50982. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  50983. }
  50984. if (options.uvs) {
  50985. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50986. for (var i = 0; i < options.uvs.length; i++) {
  50987. uvs[i * 2] = options.uvs[i].x;
  50988. uvs[i * 2 + 1] = options.uvs[i].y;
  50989. }
  50990. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  50991. }
  50992. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  50993. var indices = instance.getIndices();
  50994. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50995. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  50996. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  50997. if (instance._closePath) {
  50998. var indexFirst = 0;
  50999. var indexLast = 0;
  51000. for (var p = 0; p < pathArray.length; p++) {
  51001. indexFirst = instance._idx[p] * 3;
  51002. if (p + 1 < pathArray.length) {
  51003. indexLast = (instance._idx[p + 1] - 1) * 3;
  51004. }
  51005. else {
  51006. indexLast = normals.length - 3;
  51007. }
  51008. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51009. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51010. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51011. normals[indexLast] = normals[indexFirst];
  51012. normals[indexLast + 1] = normals[indexFirst + 1];
  51013. normals[indexLast + 2] = normals[indexFirst + 2];
  51014. }
  51015. }
  51016. if (!(instance.areNormalsFrozen)) {
  51017. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51018. }
  51019. }
  51020. return instance;
  51021. }
  51022. else {
  51023. var ribbon = new BABYLON.Mesh(name, scene);
  51024. ribbon._originalBuilderSideOrientation = sideOrientation;
  51025. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51026. if (closePath) {
  51027. ribbon._idx = vertexData._idx;
  51028. }
  51029. ribbon._closePath = closePath;
  51030. ribbon._closeArray = closeArray;
  51031. vertexData.applyToMesh(ribbon, updatable);
  51032. return ribbon;
  51033. }
  51034. };
  51035. /**
  51036. * Creates a cylinder or a cone mesh.
  51037. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51038. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51039. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51040. * 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.
  51041. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51042. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51043. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51044. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51045. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51046. * 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).
  51047. * 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
  51048. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51049. * 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
  51050. * 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.
  51051. * If `enclose` is false, a ring surface is one element.
  51052. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51053. * 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
  51054. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51055. * 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).
  51056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51058. */
  51059. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51060. var cylinder = new BABYLON.Mesh(name, scene);
  51061. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51062. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51063. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51064. vertexData.applyToMesh(cylinder, options.updatable);
  51065. return cylinder;
  51066. };
  51067. /**
  51068. * Creates a torus mesh.
  51069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51070. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51071. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51072. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51074. * 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).
  51075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51077. */
  51078. MeshBuilder.CreateTorus = function (name, options, scene) {
  51079. var torus = new BABYLON.Mesh(name, scene);
  51080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51081. torus._originalBuilderSideOrientation = options.sideOrientation;
  51082. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51083. vertexData.applyToMesh(torus, options.updatable);
  51084. return torus;
  51085. };
  51086. /**
  51087. * Creates a torus knot mesh.
  51088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51089. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51090. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51091. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51092. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51094. * 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).
  51095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51097. */
  51098. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51099. var torusKnot = new BABYLON.Mesh(name, scene);
  51100. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51101. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51102. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51103. vertexData.applyToMesh(torusKnot, options.updatable);
  51104. return torusKnot;
  51105. };
  51106. /**
  51107. * Creates a line system mesh.
  51108. * A line system is a pool of many lines gathered in a single mesh.
  51109. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51110. * 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.
  51111. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51112. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51113. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  51114. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51115. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51116. * 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
  51117. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51119. */
  51120. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51121. var instance = options.instance;
  51122. var lines = options.lines;
  51123. var colors = options.colors;
  51124. if (instance) {
  51125. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51126. var vertexColor;
  51127. var lineColors;
  51128. if (colors) {
  51129. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51130. }
  51131. var i = 0;
  51132. var c = 0;
  51133. for (var l = 0; l < lines.length; l++) {
  51134. var points = lines[l];
  51135. for (var p = 0; p < points.length; p++) {
  51136. positions[i] = points[p].x;
  51137. positions[i + 1] = points[p].y;
  51138. positions[i + 2] = points[p].z;
  51139. if (colors && vertexColor) {
  51140. lineColors = colors[l];
  51141. vertexColor[c] = lineColors[p].r;
  51142. vertexColor[c + 1] = lineColors[p].g;
  51143. vertexColor[c + 2] = lineColors[p].b;
  51144. vertexColor[c + 3] = lineColors[p].a;
  51145. c += 4;
  51146. }
  51147. i += 3;
  51148. }
  51149. }
  51150. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51151. if (colors && vertexColor) {
  51152. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51153. }
  51154. return instance;
  51155. }
  51156. // line system creation
  51157. var useVertexColor = (colors) ? true : false;
  51158. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51159. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51160. vertexData.applyToMesh(lineSystem, options.updatable);
  51161. return lineSystem;
  51162. };
  51163. /**
  51164. * Creates a line mesh.
  51165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51166. * 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.
  51167. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51168. * The parameter `points` is an array successive Vector3.
  51169. * 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
  51170. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51171. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51172. * When updating an instance, remember that only point positions can change, not the number of points.
  51173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51174. */
  51175. MeshBuilder.CreateLines = function (name, options, scene) {
  51176. if (scene === void 0) { scene = null; }
  51177. var colors = (options.colors) ? [options.colors] : null;
  51178. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51179. return lines;
  51180. };
  51181. /**
  51182. * Creates a dashed line mesh.
  51183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51184. * 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.
  51185. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51186. * The parameter `points` is an array successive Vector3.
  51187. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51188. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51189. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51190. * 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
  51191. * When updating an instance, remember that only point positions can change, not the number of points.
  51192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51193. */
  51194. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51195. if (scene === void 0) { scene = null; }
  51196. var points = options.points;
  51197. var instance = options.instance;
  51198. var gapSize = options.gapSize || 1;
  51199. var dashSize = options.dashSize || 3;
  51200. if (instance) {
  51201. var positionFunction = function (positions) {
  51202. var curvect = BABYLON.Vector3.Zero();
  51203. var nbSeg = positions.length / 6;
  51204. var lg = 0;
  51205. var nb = 0;
  51206. var shft = 0;
  51207. var dashshft = 0;
  51208. var curshft = 0;
  51209. var p = 0;
  51210. var i = 0;
  51211. var j = 0;
  51212. for (i = 0; i < points.length - 1; i++) {
  51213. points[i + 1].subtractToRef(points[i], curvect);
  51214. lg += curvect.length();
  51215. }
  51216. shft = lg / nbSeg;
  51217. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51218. for (i = 0; i < points.length - 1; i++) {
  51219. points[i + 1].subtractToRef(points[i], curvect);
  51220. nb = Math.floor(curvect.length() / shft);
  51221. curvect.normalize();
  51222. j = 0;
  51223. while (j < nb && p < positions.length) {
  51224. curshft = shft * j;
  51225. positions[p] = points[i].x + curshft * curvect.x;
  51226. positions[p + 1] = points[i].y + curshft * curvect.y;
  51227. positions[p + 2] = points[i].z + curshft * curvect.z;
  51228. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51229. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51230. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51231. p += 6;
  51232. j++;
  51233. }
  51234. }
  51235. while (p < positions.length) {
  51236. positions[p] = points[i].x;
  51237. positions[p + 1] = points[i].y;
  51238. positions[p + 2] = points[i].z;
  51239. p += 3;
  51240. }
  51241. };
  51242. instance.updateMeshPositions(positionFunction, false);
  51243. return instance;
  51244. }
  51245. // dashed lines creation
  51246. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51247. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51248. vertexData.applyToMesh(dashedLines, options.updatable);
  51249. dashedLines.dashSize = dashSize;
  51250. dashedLines.gapSize = gapSize;
  51251. return dashedLines;
  51252. };
  51253. /**
  51254. * Creates an extruded shape mesh.
  51255. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  51256. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51257. *
  51258. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51259. * 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
  51260. * extruded along the Z axis.
  51261. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51262. * 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.
  51263. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51264. * 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
  51265. * 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
  51266. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51268. * 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).
  51269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51270. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51272. */
  51273. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51274. if (scene === void 0) { scene = null; }
  51275. var path = options.path;
  51276. var shape = options.shape;
  51277. var scale = options.scale || 1;
  51278. var rotation = options.rotation || 0;
  51279. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51280. var updatable = options.updatable;
  51281. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51282. var instance = options.instance || null;
  51283. var invertUV = options.invertUV || false;
  51284. 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);
  51285. };
  51286. /**
  51287. * Creates an custom extruded shape mesh.
  51288. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  51289. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51290. *
  51291. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51292. * 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
  51293. * extruded along the Z axis.
  51294. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51295. * 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
  51296. * and the distance of this point from the begining of the path :
  51297. * ```javascript
  51298. * var rotationFunction = function(i, distance) {
  51299. * // do things
  51300. * return rotationValue; }
  51301. * ```
  51302. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51303. * 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
  51304. * and the distance of this point from the begining of the path :
  51305. * ```javascript
  51306. * var scaleFunction = function(i, distance) {
  51307. * // do things
  51308. * return scaleValue;}
  51309. * ```
  51310. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51311. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51312. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51313. * 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
  51314. * 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
  51315. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51316. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51317. * 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).
  51318. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51319. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51321. */
  51322. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51323. var path = options.path;
  51324. var shape = options.shape;
  51325. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51326. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51327. var ribbonCloseArray = options.ribbonCloseArray || false;
  51328. var ribbonClosePath = options.ribbonClosePath || false;
  51329. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51330. var updatable = options.updatable;
  51331. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51332. var instance = options.instance;
  51333. var invertUV = options.invertUV || false;
  51334. 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);
  51335. };
  51336. /**
  51337. * Creates lathe mesh.
  51338. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51340. *
  51341. * 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
  51342. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51343. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51344. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51345. * 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.
  51346. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51347. * 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
  51348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51349. * 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).
  51350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51351. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51353. */
  51354. MeshBuilder.CreateLathe = function (name, options, scene) {
  51355. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51356. var closed = (options.closed === undefined) ? true : options.closed;
  51357. var shape = options.shape;
  51358. var radius = options.radius || 1;
  51359. var tessellation = options.tessellation || 64;
  51360. var updatable = options.updatable;
  51361. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51362. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51363. var pi2 = Math.PI * 2;
  51364. var paths = new Array();
  51365. var invertUV = options.invertUV || false;
  51366. var i = 0;
  51367. var p = 0;
  51368. var step = pi2 / tessellation * arc;
  51369. var rotated;
  51370. var path = new Array();
  51371. ;
  51372. for (i = 0; i <= tessellation; i++) {
  51373. var path = [];
  51374. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51375. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51376. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51377. }
  51378. for (p = 0; p < shape.length; p++) {
  51379. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51380. path.push(rotated);
  51381. }
  51382. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51383. 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));
  51384. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51385. }
  51386. paths.push(path);
  51387. }
  51388. // lathe ribbon
  51389. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51390. return lathe;
  51391. };
  51392. /**
  51393. * Creates a plane mesh.
  51394. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51395. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51396. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51397. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51399. * 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).
  51400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51402. */
  51403. MeshBuilder.CreatePlane = function (name, options, scene) {
  51404. var plane = new BABYLON.Mesh(name, scene);
  51405. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51406. plane._originalBuilderSideOrientation = options.sideOrientation;
  51407. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51408. vertexData.applyToMesh(plane, options.updatable);
  51409. if (options.sourcePlane) {
  51410. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51411. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51412. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51413. plane.rotate(vectorProduct, product);
  51414. }
  51415. return plane;
  51416. };
  51417. /**
  51418. * Creates a ground mesh.
  51419. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51420. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51421. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51423. */
  51424. MeshBuilder.CreateGround = function (name, options, scene) {
  51425. var ground = new BABYLON.GroundMesh(name, scene);
  51426. ground._setReady(false);
  51427. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51428. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51429. ground._width = options.width || 1;
  51430. ground._height = options.height || 1;
  51431. ground._maxX = ground._width / 2;
  51432. ground._maxZ = ground._height / 2;
  51433. ground._minX = -ground._maxX;
  51434. ground._minZ = -ground._maxZ;
  51435. var vertexData = BABYLON.VertexData.CreateGround(options);
  51436. vertexData.applyToMesh(ground, options.updatable);
  51437. ground._setReady(true);
  51438. return ground;
  51439. };
  51440. /**
  51441. * Creates a tiled ground mesh.
  51442. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51443. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51444. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51445. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51446. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51447. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51448. * numbers of subdivisions on the ground width and height of each tile.
  51449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51450. */
  51451. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51452. var tiledGround = new BABYLON.Mesh(name, scene);
  51453. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51454. vertexData.applyToMesh(tiledGround, options.updatable);
  51455. return tiledGround;
  51456. };
  51457. /**
  51458. * Creates a ground mesh from a height map.
  51459. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51460. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51461. * The parameter `url` sets the URL of the height map image resource.
  51462. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51463. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51464. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51465. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51466. * 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.
  51467. * 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).
  51468. * This function is passed the newly built mesh :
  51469. * ```javascript
  51470. * function(mesh) { // do things
  51471. * return; }
  51472. * ```
  51473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51474. */
  51475. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  51476. var width = options.width || 10.0;
  51477. var height = options.height || 10.0;
  51478. var subdivisions = options.subdivisions || 1 | 0;
  51479. var minHeight = options.minHeight || 0.0;
  51480. var maxHeight = options.maxHeight || 1.0;
  51481. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  51482. var updatable = options.updatable;
  51483. var onReady = options.onReady;
  51484. var ground = new BABYLON.GroundMesh(name, scene);
  51485. ground._subdivisionsX = subdivisions;
  51486. ground._subdivisionsY = subdivisions;
  51487. ground._width = width;
  51488. ground._height = height;
  51489. ground._maxX = ground._width / 2.0;
  51490. ground._maxZ = ground._height / 2.0;
  51491. ground._minX = -ground._maxX;
  51492. ground._minZ = -ground._maxZ;
  51493. ground._setReady(false);
  51494. var onload = function (img) {
  51495. // Getting height map data
  51496. var canvas = document.createElement("canvas");
  51497. var context = canvas.getContext("2d");
  51498. if (!context) {
  51499. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  51500. }
  51501. if (scene.isDisposed) {
  51502. return;
  51503. }
  51504. var bufferWidth = img.width;
  51505. var bufferHeight = img.height;
  51506. canvas.width = bufferWidth;
  51507. canvas.height = bufferHeight;
  51508. context.drawImage(img, 0, 0);
  51509. // Create VertexData from map data
  51510. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  51511. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  51512. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  51513. width: width, height: height,
  51514. subdivisions: subdivisions,
  51515. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  51516. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  51517. });
  51518. vertexData.applyToMesh(ground, updatable);
  51519. ground._setReady(true);
  51520. //execute ready callback, if set
  51521. if (onReady) {
  51522. onReady(ground);
  51523. }
  51524. };
  51525. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  51526. return ground;
  51527. };
  51528. /**
  51529. * Creates a polygon mesh.
  51530. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  51531. * 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.
  51532. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51534. * 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).
  51535. * Remember you can only change the shape positions, not their number when updating a polygon.
  51536. */
  51537. MeshBuilder.CreatePolygon = function (name, options, scene) {
  51538. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51539. var shape = options.shape;
  51540. var holes = options.holes || [];
  51541. var depth = options.depth || 0;
  51542. var contours = [];
  51543. var hole = [];
  51544. for (var i = 0; i < shape.length; i++) {
  51545. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  51546. }
  51547. var epsilon = 0.00000001;
  51548. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  51549. contours.pop();
  51550. }
  51551. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  51552. for (var hNb = 0; hNb < holes.length; hNb++) {
  51553. hole = [];
  51554. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  51555. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  51556. }
  51557. polygonTriangulation.addHole(hole);
  51558. }
  51559. var polygon = polygonTriangulation.build(options.updatable, depth);
  51560. polygon._originalBuilderSideOrientation = options.sideOrientation;
  51561. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  51562. vertexData.applyToMesh(polygon, options.updatable);
  51563. return polygon;
  51564. };
  51565. ;
  51566. /**
  51567. * Creates an extruded polygon mesh, with depth in the Y direction.
  51568. * 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).
  51569. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51570. */
  51571. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  51572. return MeshBuilder.CreatePolygon(name, options, scene);
  51573. };
  51574. ;
  51575. /**
  51576. * Creates a tube mesh.
  51577. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  51578. *
  51579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  51580. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  51581. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  51582. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  51583. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  51584. * 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.
  51585. * It must return a radius value (positive float) :
  51586. * ```javascript
  51587. * var radiusFunction = function(i, distance) {
  51588. * // do things
  51589. * return radius; }
  51590. * ```
  51591. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  51592. * 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
  51593. * 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
  51594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51595. * 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).
  51596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51597. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51599. */
  51600. MeshBuilder.CreateTube = function (name, options, scene) {
  51601. var path = options.path;
  51602. var instance = options.instance;
  51603. var radius = 1.0;
  51604. if (instance) {
  51605. radius = instance.radius;
  51606. }
  51607. if (options.radius !== undefined) {
  51608. radius = options.radius;
  51609. }
  51610. ;
  51611. var tessellation = options.tessellation || 64 | 0;
  51612. var radiusFunction = options.radiusFunction || null;
  51613. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51614. var invertUV = options.invertUV || false;
  51615. var updatable = options.updatable;
  51616. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51617. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  51618. // tube geometry
  51619. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  51620. var tangents = path3D.getTangents();
  51621. var normals = path3D.getNormals();
  51622. var distances = path3D.getDistances();
  51623. var pi2 = Math.PI * 2;
  51624. var step = pi2 / tessellation * arc;
  51625. var returnRadius = function () { return radius; };
  51626. var radiusFunctionFinal = radiusFunction || returnRadius;
  51627. var circlePath;
  51628. var rad;
  51629. var normal;
  51630. var rotated;
  51631. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51632. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51633. for (var i = 0; i < path.length; i++) {
  51634. rad = radiusFunctionFinal(i, distances[i]); // current radius
  51635. circlePath = Array(); // current circle array
  51636. normal = normals[i]; // current normal
  51637. for (var t = 0; t < tessellation; t++) {
  51638. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  51639. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  51640. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  51641. rotated.scaleInPlace(rad).addInPlace(path[i]);
  51642. circlePath[t] = rotated;
  51643. }
  51644. circlePaths[index] = circlePath;
  51645. index++;
  51646. }
  51647. // cap
  51648. var capPath = function (nbPoints, pathIndex) {
  51649. var pointCap = Array();
  51650. for (var i = 0; i < nbPoints; i++) {
  51651. pointCap.push(path[pathIndex]);
  51652. }
  51653. return pointCap;
  51654. };
  51655. switch (cap) {
  51656. case BABYLON.Mesh.NO_CAP:
  51657. break;
  51658. case BABYLON.Mesh.CAP_START:
  51659. circlePaths[0] = capPath(tessellation, 0);
  51660. circlePaths[1] = circlePaths[2].slice(0);
  51661. break;
  51662. case BABYLON.Mesh.CAP_END:
  51663. circlePaths[index] = circlePaths[index - 1].slice(0);
  51664. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51665. break;
  51666. case BABYLON.Mesh.CAP_ALL:
  51667. circlePaths[0] = capPath(tessellation, 0);
  51668. circlePaths[1] = circlePaths[2].slice(0);
  51669. circlePaths[index] = circlePaths[index - 1].slice(0);
  51670. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51671. break;
  51672. default:
  51673. break;
  51674. }
  51675. return circlePaths;
  51676. };
  51677. var path3D;
  51678. var pathArray;
  51679. if (instance) {
  51680. var arc = options.arc || instance.arc;
  51681. path3D = (instance.path3D).update(path);
  51682. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  51683. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  51684. instance.path3D = path3D;
  51685. instance.pathArray = pathArray;
  51686. instance.arc = arc;
  51687. instance.radius = radius;
  51688. return instance;
  51689. }
  51690. // tube creation
  51691. path3D = new BABYLON.Path3D(path);
  51692. var newPathArray = new Array();
  51693. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51694. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  51695. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51696. tube.pathArray = pathArray;
  51697. tube.path3D = path3D;
  51698. tube.tessellation = tessellation;
  51699. tube.cap = cap;
  51700. tube.arc = options.arc;
  51701. tube.radius = radius;
  51702. return tube;
  51703. };
  51704. /**
  51705. * Creates a polyhedron mesh.
  51706. *
  51707. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  51708. * 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
  51709. * to choose the wanted type.
  51710. * The parameter `size` (positive float, default 1) sets the polygon size.
  51711. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  51712. * 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`.
  51713. * 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
  51714. * 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)`).
  51715. * 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
  51716. * 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.
  51717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51718. * 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).
  51719. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51721. */
  51722. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  51723. var polyhedron = new BABYLON.Mesh(name, scene);
  51724. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51725. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  51726. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  51727. vertexData.applyToMesh(polyhedron, options.updatable);
  51728. return polyhedron;
  51729. };
  51730. /**
  51731. * Creates a decal mesh.
  51732. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  51733. * 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.
  51734. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  51735. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  51736. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  51737. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  51738. */
  51739. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  51740. var indices = sourceMesh.getIndices();
  51741. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51742. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51743. var position = options.position || BABYLON.Vector3.Zero();
  51744. var normal = options.normal || BABYLON.Vector3.Up();
  51745. var size = options.size || BABYLON.Vector3.One();
  51746. var angle = options.angle || 0;
  51747. // Getting correct rotation
  51748. if (!normal) {
  51749. var target = new BABYLON.Vector3(0, 0, 1);
  51750. var camera = sourceMesh.getScene().activeCamera;
  51751. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  51752. normal = camera.globalPosition.subtract(cameraWorldTarget);
  51753. }
  51754. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  51755. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  51756. var pitch = Math.atan2(normal.y, len);
  51757. // Matrix
  51758. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  51759. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  51760. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  51761. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  51762. var vertexData = new BABYLON.VertexData();
  51763. vertexData.indices = [];
  51764. vertexData.positions = [];
  51765. vertexData.normals = [];
  51766. vertexData.uvs = [];
  51767. var currentVertexDataIndex = 0;
  51768. var extractDecalVector3 = function (indexId) {
  51769. var result = new BABYLON.PositionNormalVertex();
  51770. if (!indices || !positions || !normals) {
  51771. return result;
  51772. }
  51773. var vertexId = indices[indexId];
  51774. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  51775. // Send vector to decal local world
  51776. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  51777. // Get normal
  51778. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  51779. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  51780. return result;
  51781. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  51782. var clip = function (vertices, axis) {
  51783. if (vertices.length === 0) {
  51784. return vertices;
  51785. }
  51786. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  51787. var clipVertices = function (v0, v1) {
  51788. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  51789. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  51790. };
  51791. var result = new Array();
  51792. for (var index = 0; index < vertices.length; index += 3) {
  51793. var v1Out;
  51794. var v2Out;
  51795. var v3Out;
  51796. var total = 0;
  51797. var nV1 = null;
  51798. var nV2 = null;
  51799. var nV3 = null;
  51800. var nV4 = null;
  51801. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  51802. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  51803. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  51804. v1Out = d1 > 0;
  51805. v2Out = d2 > 0;
  51806. v3Out = d3 > 0;
  51807. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  51808. switch (total) {
  51809. case 0:
  51810. result.push(vertices[index]);
  51811. result.push(vertices[index + 1]);
  51812. result.push(vertices[index + 2]);
  51813. break;
  51814. case 1:
  51815. if (v1Out) {
  51816. nV1 = vertices[index + 1];
  51817. nV2 = vertices[index + 2];
  51818. nV3 = clipVertices(vertices[index], nV1);
  51819. nV4 = clipVertices(vertices[index], nV2);
  51820. }
  51821. if (v2Out) {
  51822. nV1 = vertices[index];
  51823. nV2 = vertices[index + 2];
  51824. nV3 = clipVertices(vertices[index + 1], nV1);
  51825. nV4 = clipVertices(vertices[index + 1], nV2);
  51826. result.push(nV3);
  51827. result.push(nV2.clone());
  51828. result.push(nV1.clone());
  51829. result.push(nV2.clone());
  51830. result.push(nV3.clone());
  51831. result.push(nV4);
  51832. break;
  51833. }
  51834. if (v3Out) {
  51835. nV1 = vertices[index];
  51836. nV2 = vertices[index + 1];
  51837. nV3 = clipVertices(vertices[index + 2], nV1);
  51838. nV4 = clipVertices(vertices[index + 2], nV2);
  51839. }
  51840. if (nV1 && nV2 && nV3 && nV4) {
  51841. result.push(nV1.clone());
  51842. result.push(nV2.clone());
  51843. result.push(nV3);
  51844. result.push(nV4);
  51845. result.push(nV3.clone());
  51846. result.push(nV2.clone());
  51847. }
  51848. break;
  51849. case 2:
  51850. if (!v1Out) {
  51851. nV1 = vertices[index].clone();
  51852. nV2 = clipVertices(nV1, vertices[index + 1]);
  51853. nV3 = clipVertices(nV1, vertices[index + 2]);
  51854. result.push(nV1);
  51855. result.push(nV2);
  51856. result.push(nV3);
  51857. }
  51858. if (!v2Out) {
  51859. nV1 = vertices[index + 1].clone();
  51860. nV2 = clipVertices(nV1, vertices[index + 2]);
  51861. nV3 = clipVertices(nV1, vertices[index]);
  51862. result.push(nV1);
  51863. result.push(nV2);
  51864. result.push(nV3);
  51865. }
  51866. if (!v3Out) {
  51867. nV1 = vertices[index + 2].clone();
  51868. nV2 = clipVertices(nV1, vertices[index]);
  51869. nV3 = clipVertices(nV1, vertices[index + 1]);
  51870. result.push(nV1);
  51871. result.push(nV2);
  51872. result.push(nV3);
  51873. }
  51874. break;
  51875. case 3:
  51876. break;
  51877. }
  51878. }
  51879. return result;
  51880. };
  51881. for (var index = 0; index < indices.length; index += 3) {
  51882. var faceVertices = new Array();
  51883. faceVertices.push(extractDecalVector3(index));
  51884. faceVertices.push(extractDecalVector3(index + 1));
  51885. faceVertices.push(extractDecalVector3(index + 2));
  51886. // Clip
  51887. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  51888. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  51889. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  51890. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  51891. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  51892. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  51893. if (faceVertices.length === 0) {
  51894. continue;
  51895. }
  51896. // Add UVs and get back to world
  51897. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  51898. var vertex = faceVertices[vIndex];
  51899. //TODO check for Int32Array | Uint32Array | Uint16Array
  51900. vertexData.indices.push(currentVertexDataIndex);
  51901. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  51902. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  51903. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  51904. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  51905. currentVertexDataIndex++;
  51906. }
  51907. }
  51908. // Return mesh
  51909. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  51910. vertexData.applyToMesh(decal);
  51911. decal.position = position.clone();
  51912. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  51913. return decal;
  51914. };
  51915. // Privates
  51916. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  51917. // extrusion geometry
  51918. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  51919. var tangents = path3D.getTangents();
  51920. var normals = path3D.getNormals();
  51921. var binormals = path3D.getBinormals();
  51922. var distances = path3D.getDistances();
  51923. var angle = 0;
  51924. var returnScale = function () { return scale !== null ? scale : 1; };
  51925. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  51926. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  51927. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  51928. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51929. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51930. for (var i = 0; i < curve.length; i++) {
  51931. var shapePath = new Array();
  51932. var angleStep = rotate(i, distances[i]);
  51933. var scaleRatio = scl(i, distances[i]);
  51934. for (var p = 0; p < shape.length; p++) {
  51935. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  51936. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  51937. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  51938. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  51939. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  51940. shapePath[p] = rotated;
  51941. }
  51942. shapePaths[index] = shapePath;
  51943. angle += angleStep;
  51944. index++;
  51945. }
  51946. // cap
  51947. var capPath = function (shapePath) {
  51948. var pointCap = Array();
  51949. var barycenter = BABYLON.Vector3.Zero();
  51950. var i;
  51951. for (i = 0; i < shapePath.length; i++) {
  51952. barycenter.addInPlace(shapePath[i]);
  51953. }
  51954. barycenter.scaleInPlace(1.0 / shapePath.length);
  51955. for (i = 0; i < shapePath.length; i++) {
  51956. pointCap.push(barycenter);
  51957. }
  51958. return pointCap;
  51959. };
  51960. switch (cap) {
  51961. case BABYLON.Mesh.NO_CAP:
  51962. break;
  51963. case BABYLON.Mesh.CAP_START:
  51964. shapePaths[0] = capPath(shapePaths[2]);
  51965. shapePaths[1] = shapePaths[2];
  51966. break;
  51967. case BABYLON.Mesh.CAP_END:
  51968. shapePaths[index] = shapePaths[index - 1];
  51969. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  51970. break;
  51971. case BABYLON.Mesh.CAP_ALL:
  51972. shapePaths[0] = capPath(shapePaths[2]);
  51973. shapePaths[1] = shapePaths[2];
  51974. shapePaths[index] = shapePaths[index - 1];
  51975. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  51976. break;
  51977. default:
  51978. break;
  51979. }
  51980. return shapePaths;
  51981. };
  51982. var path3D;
  51983. var pathArray;
  51984. if (instance) {
  51985. path3D = (instance.path3D).update(curve);
  51986. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  51987. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  51988. return instance;
  51989. }
  51990. // extruded shape creation
  51991. path3D = new BABYLON.Path3D(curve);
  51992. var newShapePaths = new Array();
  51993. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51994. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  51995. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  51996. extrudedGeneric.pathArray = pathArray;
  51997. extrudedGeneric.path3D = path3D;
  51998. extrudedGeneric.cap = cap;
  51999. return extrudedGeneric;
  52000. };
  52001. return MeshBuilder;
  52002. }());
  52003. BABYLON.MeshBuilder = MeshBuilder;
  52004. })(BABYLON || (BABYLON = {}));
  52005. //# sourceMappingURL=babylon.meshBuilder.js.map
  52006. var BABYLON;
  52007. (function (BABYLON) {
  52008. var AudioEngine = /** @class */ (function () {
  52009. function AudioEngine() {
  52010. this._audioContext = null;
  52011. this._audioContextInitialized = false;
  52012. this.canUseWebAudio = false;
  52013. this.WarnedWebAudioUnsupported = false;
  52014. this.unlocked = false;
  52015. this.isMP3supported = false;
  52016. this.isOGGsupported = false;
  52017. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52018. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52019. this.canUseWebAudio = true;
  52020. }
  52021. var audioElem = document.createElement('audio');
  52022. try {
  52023. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52024. this.isMP3supported = true;
  52025. }
  52026. }
  52027. catch (e) {
  52028. // protect error during capability check.
  52029. }
  52030. try {
  52031. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52032. this.isOGGsupported = true;
  52033. }
  52034. }
  52035. catch (e) {
  52036. // protect error during capability check.
  52037. }
  52038. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52039. this._unlockiOSaudio();
  52040. }
  52041. else {
  52042. this.unlocked = true;
  52043. }
  52044. }
  52045. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52046. get: function () {
  52047. if (!this._audioContextInitialized) {
  52048. this._initializeAudioContext();
  52049. }
  52050. return this._audioContext;
  52051. },
  52052. enumerable: true,
  52053. configurable: true
  52054. });
  52055. AudioEngine.prototype._unlockiOSaudio = function () {
  52056. var _this = this;
  52057. var unlockaudio = function () {
  52058. if (!_this.audioContext) {
  52059. return;
  52060. }
  52061. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52062. var source = _this.audioContext.createBufferSource();
  52063. source.buffer = buffer;
  52064. source.connect(_this.audioContext.destination);
  52065. source.start(0);
  52066. setTimeout(function () {
  52067. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52068. _this.unlocked = true;
  52069. window.removeEventListener('touchend', unlockaudio, false);
  52070. if (_this.onAudioUnlocked) {
  52071. _this.onAudioUnlocked();
  52072. }
  52073. }
  52074. }, 0);
  52075. };
  52076. window.addEventListener('touchend', unlockaudio, false);
  52077. };
  52078. AudioEngine.prototype._initializeAudioContext = function () {
  52079. try {
  52080. if (this.canUseWebAudio) {
  52081. this._audioContext = new AudioContext();
  52082. // create a global volume gain node
  52083. this.masterGain = this._audioContext.createGain();
  52084. this.masterGain.gain.value = 1;
  52085. this.masterGain.connect(this._audioContext.destination);
  52086. this._audioContextInitialized = true;
  52087. }
  52088. }
  52089. catch (e) {
  52090. this.canUseWebAudio = false;
  52091. BABYLON.Tools.Error("Web Audio: " + e.message);
  52092. }
  52093. };
  52094. AudioEngine.prototype.dispose = function () {
  52095. if (this.canUseWebAudio && this._audioContextInitialized) {
  52096. if (this._connectedAnalyser && this._audioContext) {
  52097. this._connectedAnalyser.stopDebugCanvas();
  52098. this._connectedAnalyser.dispose();
  52099. this.masterGain.disconnect();
  52100. this.masterGain.connect(this._audioContext.destination);
  52101. this._connectedAnalyser = null;
  52102. }
  52103. this.masterGain.gain.value = 1;
  52104. }
  52105. this.WarnedWebAudioUnsupported = false;
  52106. };
  52107. AudioEngine.prototype.getGlobalVolume = function () {
  52108. if (this.canUseWebAudio && this._audioContextInitialized) {
  52109. return this.masterGain.gain.value;
  52110. }
  52111. else {
  52112. return -1;
  52113. }
  52114. };
  52115. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52116. if (this.canUseWebAudio && this._audioContextInitialized) {
  52117. this.masterGain.gain.value = newVolume;
  52118. }
  52119. };
  52120. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52121. if (this._connectedAnalyser) {
  52122. this._connectedAnalyser.stopDebugCanvas();
  52123. }
  52124. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52125. this._connectedAnalyser = analyser;
  52126. this.masterGain.disconnect();
  52127. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52128. }
  52129. };
  52130. return AudioEngine;
  52131. }());
  52132. BABYLON.AudioEngine = AudioEngine;
  52133. })(BABYLON || (BABYLON = {}));
  52134. //# sourceMappingURL=babylon.audioEngine.js.map
  52135. var BABYLON;
  52136. (function (BABYLON) {
  52137. var Sound = /** @class */ (function () {
  52138. /**
  52139. * Create a sound and attach it to a scene
  52140. * @param name Name of your sound
  52141. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52142. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52143. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52144. */
  52145. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52146. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52147. var _this = this;
  52148. this.autoplay = false;
  52149. this.loop = false;
  52150. this.useCustomAttenuation = false;
  52151. this.spatialSound = false;
  52152. this.refDistance = 1;
  52153. this.rolloffFactor = 1;
  52154. this.maxDistance = 100;
  52155. this.distanceModel = "linear";
  52156. this._panningModel = "equalpower";
  52157. this._playbackRate = 1;
  52158. this._streaming = false;
  52159. this._startTime = 0;
  52160. this._startOffset = 0;
  52161. this._position = BABYLON.Vector3.Zero();
  52162. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52163. this._volume = 1;
  52164. this._isReadyToPlay = false;
  52165. this.isPlaying = false;
  52166. this.isPaused = false;
  52167. this._isDirectional = false;
  52168. // Used if you'd like to create a directional sound.
  52169. // If not set, the sound will be omnidirectional
  52170. this._coneInnerAngle = 360;
  52171. this._coneOuterAngle = 360;
  52172. this._coneOuterGain = 0;
  52173. this._isOutputConnected = false;
  52174. this._urlType = "Unknown";
  52175. this.name = name;
  52176. this._scene = scene;
  52177. this._readyToPlayCallback = readyToPlayCallback;
  52178. // Default custom attenuation function is a linear attenuation
  52179. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52180. if (currentDistance < maxDistance) {
  52181. return currentVolume * (1 - currentDistance / maxDistance);
  52182. }
  52183. else {
  52184. return 0;
  52185. }
  52186. };
  52187. if (options) {
  52188. this.autoplay = options.autoplay || false;
  52189. this.loop = options.loop || false;
  52190. // if volume === 0, we need another way to check this option
  52191. if (options.volume !== undefined) {
  52192. this._volume = options.volume;
  52193. }
  52194. this.spatialSound = options.spatialSound || false;
  52195. this.maxDistance = options.maxDistance || 100;
  52196. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52197. this.rolloffFactor = options.rolloffFactor || 1;
  52198. this.refDistance = options.refDistance || 1;
  52199. this.distanceModel = options.distanceModel || "linear";
  52200. this._playbackRate = options.playbackRate || 1;
  52201. this._streaming = options.streaming || false;
  52202. }
  52203. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52204. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52205. this._soundGain.gain.value = this._volume;
  52206. this._inputAudioNode = this._soundGain;
  52207. this._ouputAudioNode = this._soundGain;
  52208. if (this.spatialSound) {
  52209. this._createSpatialParameters();
  52210. }
  52211. this._scene.mainSoundTrack.AddSound(this);
  52212. var validParameter = true;
  52213. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52214. if (urlOrArrayBuffer) {
  52215. if (typeof (urlOrArrayBuffer) === "string")
  52216. this._urlType = "String";
  52217. if (Array.isArray(urlOrArrayBuffer))
  52218. this._urlType = "Array";
  52219. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52220. this._urlType = "ArrayBuffer";
  52221. var urls = [];
  52222. var codecSupportedFound = false;
  52223. switch (this._urlType) {
  52224. case "ArrayBuffer":
  52225. if (urlOrArrayBuffer.byteLength > 0) {
  52226. codecSupportedFound = true;
  52227. this._soundLoaded(urlOrArrayBuffer);
  52228. }
  52229. break;
  52230. case "String":
  52231. urls.push(urlOrArrayBuffer);
  52232. case "Array":
  52233. if (urls.length === 0)
  52234. urls = urlOrArrayBuffer;
  52235. // If we found a supported format, we load it immediately and stop the loop
  52236. for (var i = 0; i < urls.length; i++) {
  52237. var url = urls[i];
  52238. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52239. codecSupportedFound = true;
  52240. }
  52241. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52242. codecSupportedFound = true;
  52243. }
  52244. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52245. codecSupportedFound = true;
  52246. }
  52247. if (url.indexOf("blob:") !== -1) {
  52248. codecSupportedFound = true;
  52249. }
  52250. if (codecSupportedFound) {
  52251. // Loading sound using XHR2
  52252. if (!this._streaming) {
  52253. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52254. }
  52255. else {
  52256. this._htmlAudioElement = new Audio(url);
  52257. this._htmlAudioElement.controls = false;
  52258. this._htmlAudioElement.loop = this.loop;
  52259. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52260. this._htmlAudioElement.preload = "auto";
  52261. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52262. _this._isReadyToPlay = true;
  52263. if (_this.autoplay) {
  52264. _this.play();
  52265. }
  52266. if (_this._readyToPlayCallback) {
  52267. _this._readyToPlayCallback();
  52268. }
  52269. });
  52270. document.body.appendChild(this._htmlAudioElement);
  52271. }
  52272. break;
  52273. }
  52274. }
  52275. break;
  52276. default:
  52277. validParameter = false;
  52278. break;
  52279. }
  52280. if (!validParameter) {
  52281. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52282. }
  52283. else {
  52284. if (!codecSupportedFound) {
  52285. this._isReadyToPlay = true;
  52286. // Simulating a ready to play event to avoid breaking code path
  52287. if (this._readyToPlayCallback) {
  52288. window.setTimeout(function () {
  52289. if (_this._readyToPlayCallback) {
  52290. _this._readyToPlayCallback();
  52291. }
  52292. }, 1000);
  52293. }
  52294. }
  52295. }
  52296. }
  52297. }
  52298. else {
  52299. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52300. this._scene.mainSoundTrack.AddSound(this);
  52301. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52302. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52303. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52304. }
  52305. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52306. if (this._readyToPlayCallback) {
  52307. window.setTimeout(function () {
  52308. if (_this._readyToPlayCallback) {
  52309. _this._readyToPlayCallback();
  52310. }
  52311. }, 1000);
  52312. }
  52313. }
  52314. }
  52315. Sound.prototype.dispose = function () {
  52316. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52317. if (this.isPlaying) {
  52318. this.stop();
  52319. }
  52320. this._isReadyToPlay = false;
  52321. if (this.soundTrackId === -1) {
  52322. this._scene.mainSoundTrack.RemoveSound(this);
  52323. }
  52324. else {
  52325. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52326. }
  52327. if (this._soundGain) {
  52328. this._soundGain.disconnect();
  52329. this._soundGain = null;
  52330. }
  52331. if (this._soundPanner) {
  52332. this._soundPanner.disconnect();
  52333. this._soundPanner = null;
  52334. }
  52335. if (this._soundSource) {
  52336. this._soundSource.disconnect();
  52337. this._soundSource = null;
  52338. }
  52339. this._audioBuffer = null;
  52340. if (this._htmlAudioElement) {
  52341. this._htmlAudioElement.pause();
  52342. this._htmlAudioElement.src = "";
  52343. document.body.removeChild(this._htmlAudioElement);
  52344. }
  52345. if (this._connectedMesh && this._registerFunc) {
  52346. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52347. this._connectedMesh = null;
  52348. }
  52349. }
  52350. };
  52351. Sound.prototype.isReady = function () {
  52352. return this._isReadyToPlay;
  52353. };
  52354. Sound.prototype._soundLoaded = function (audioData) {
  52355. var _this = this;
  52356. if (!BABYLON.Engine.audioEngine.audioContext) {
  52357. return;
  52358. }
  52359. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52360. _this._audioBuffer = buffer;
  52361. _this._isReadyToPlay = true;
  52362. if (_this.autoplay) {
  52363. _this.play();
  52364. }
  52365. if (_this._readyToPlayCallback) {
  52366. _this._readyToPlayCallback();
  52367. }
  52368. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52369. };
  52370. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52371. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52372. this._audioBuffer = audioBuffer;
  52373. this._isReadyToPlay = true;
  52374. }
  52375. };
  52376. Sound.prototype.updateOptions = function (options) {
  52377. if (options) {
  52378. this.loop = options.loop || this.loop;
  52379. this.maxDistance = options.maxDistance || this.maxDistance;
  52380. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52381. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52382. this.refDistance = options.refDistance || this.refDistance;
  52383. this.distanceModel = options.distanceModel || this.distanceModel;
  52384. this._playbackRate = options.playbackRate || this._playbackRate;
  52385. this._updateSpatialParameters();
  52386. if (this.isPlaying) {
  52387. if (this._streaming) {
  52388. this._htmlAudioElement.playbackRate = this._playbackRate;
  52389. }
  52390. else {
  52391. if (this._soundSource) {
  52392. this._soundSource.playbackRate.value = this._playbackRate;
  52393. }
  52394. }
  52395. }
  52396. }
  52397. };
  52398. Sound.prototype._createSpatialParameters = function () {
  52399. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52400. if (this._scene.headphone) {
  52401. this._panningModel = "HRTF";
  52402. }
  52403. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52404. this._updateSpatialParameters();
  52405. this._soundPanner.connect(this._ouputAudioNode);
  52406. this._inputAudioNode = this._soundPanner;
  52407. }
  52408. };
  52409. Sound.prototype._updateSpatialParameters = function () {
  52410. if (this.spatialSound && this._soundPanner) {
  52411. if (this.useCustomAttenuation) {
  52412. // Tricks to disable in a way embedded Web Audio attenuation
  52413. this._soundPanner.distanceModel = "linear";
  52414. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52415. this._soundPanner.refDistance = 1;
  52416. this._soundPanner.rolloffFactor = 1;
  52417. this._soundPanner.panningModel = this._panningModel;
  52418. }
  52419. else {
  52420. this._soundPanner.distanceModel = this.distanceModel;
  52421. this._soundPanner.maxDistance = this.maxDistance;
  52422. this._soundPanner.refDistance = this.refDistance;
  52423. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52424. this._soundPanner.panningModel = this._panningModel;
  52425. }
  52426. }
  52427. };
  52428. Sound.prototype.switchPanningModelToHRTF = function () {
  52429. this._panningModel = "HRTF";
  52430. this._switchPanningModel();
  52431. };
  52432. Sound.prototype.switchPanningModelToEqualPower = function () {
  52433. this._panningModel = "equalpower";
  52434. this._switchPanningModel();
  52435. };
  52436. Sound.prototype._switchPanningModel = function () {
  52437. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52438. this._soundPanner.panningModel = this._panningModel;
  52439. }
  52440. };
  52441. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52442. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52443. if (this._isOutputConnected) {
  52444. this._ouputAudioNode.disconnect();
  52445. }
  52446. this._ouputAudioNode.connect(soundTrackAudioNode);
  52447. this._isOutputConnected = true;
  52448. }
  52449. };
  52450. /**
  52451. * Transform this sound into a directional source
  52452. * @param coneInnerAngle Size of the inner cone in degree
  52453. * @param coneOuterAngle Size of the outer cone in degree
  52454. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52455. */
  52456. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52457. if (coneOuterAngle < coneInnerAngle) {
  52458. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52459. return;
  52460. }
  52461. this._coneInnerAngle = coneInnerAngle;
  52462. this._coneOuterAngle = coneOuterAngle;
  52463. this._coneOuterGain = coneOuterGain;
  52464. this._isDirectional = true;
  52465. if (this.isPlaying && this.loop) {
  52466. this.stop();
  52467. this.play();
  52468. }
  52469. };
  52470. Sound.prototype.setPosition = function (newPosition) {
  52471. this._position = newPosition;
  52472. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52473. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52474. }
  52475. };
  52476. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  52477. this._localDirection = newLocalDirection;
  52478. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  52479. this._updateDirection();
  52480. }
  52481. };
  52482. Sound.prototype._updateDirection = function () {
  52483. if (!this._connectedMesh || !this._soundPanner) {
  52484. return;
  52485. }
  52486. var mat = this._connectedMesh.getWorldMatrix();
  52487. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  52488. direction.normalize();
  52489. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  52490. };
  52491. Sound.prototype.updateDistanceFromListener = function () {
  52492. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  52493. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  52494. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  52495. }
  52496. };
  52497. Sound.prototype.setAttenuationFunction = function (callback) {
  52498. this._customAttenuationFunction = callback;
  52499. };
  52500. /**
  52501. * Play the sound
  52502. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  52503. * @param offset (optional) Start the sound setting it at a specific time
  52504. */
  52505. Sound.prototype.play = function (time, offset) {
  52506. var _this = this;
  52507. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  52508. try {
  52509. if (this._startOffset < 0) {
  52510. time = -this._startOffset;
  52511. this._startOffset = 0;
  52512. }
  52513. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52514. if (!this._soundSource || !this._streamingSource) {
  52515. if (this.spatialSound && this._soundPanner) {
  52516. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52517. if (this._isDirectional) {
  52518. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  52519. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  52520. this._soundPanner.coneOuterGain = this._coneOuterGain;
  52521. if (this._connectedMesh) {
  52522. this._updateDirection();
  52523. }
  52524. else {
  52525. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  52526. }
  52527. }
  52528. }
  52529. }
  52530. if (this._streaming) {
  52531. if (!this._streamingSource) {
  52532. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  52533. this._htmlAudioElement.onended = function () { _this._onended(); };
  52534. this._htmlAudioElement.playbackRate = this._playbackRate;
  52535. }
  52536. this._streamingSource.disconnect();
  52537. this._streamingSource.connect(this._inputAudioNode);
  52538. this._htmlAudioElement.play();
  52539. }
  52540. else {
  52541. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  52542. this._soundSource.buffer = this._audioBuffer;
  52543. this._soundSource.connect(this._inputAudioNode);
  52544. this._soundSource.loop = this.loop;
  52545. this._soundSource.playbackRate.value = this._playbackRate;
  52546. this._soundSource.onended = function () { _this._onended(); };
  52547. if (this._soundSource.buffer) {
  52548. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  52549. }
  52550. }
  52551. this._startTime = startTime;
  52552. this.isPlaying = true;
  52553. this.isPaused = false;
  52554. }
  52555. catch (ex) {
  52556. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  52557. }
  52558. }
  52559. };
  52560. Sound.prototype._onended = function () {
  52561. this.isPlaying = false;
  52562. if (this.onended) {
  52563. this.onended();
  52564. }
  52565. };
  52566. /**
  52567. * Stop the sound
  52568. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  52569. */
  52570. Sound.prototype.stop = function (time) {
  52571. if (this.isPlaying) {
  52572. if (this._streaming) {
  52573. this._htmlAudioElement.pause();
  52574. // Test needed for Firefox or it will generate an Invalid State Error
  52575. if (this._htmlAudioElement.currentTime > 0) {
  52576. this._htmlAudioElement.currentTime = 0;
  52577. }
  52578. }
  52579. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  52580. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52581. this._soundSource.stop(stopTime);
  52582. this._soundSource.onended = function () { };
  52583. if (!this.isPaused) {
  52584. this._startOffset = 0;
  52585. }
  52586. }
  52587. this.isPlaying = false;
  52588. }
  52589. };
  52590. Sound.prototype.pause = function () {
  52591. if (this.isPlaying) {
  52592. this.isPaused = true;
  52593. if (this._streaming) {
  52594. this._htmlAudioElement.pause();
  52595. }
  52596. else if (BABYLON.Engine.audioEngine.audioContext) {
  52597. this.stop(0);
  52598. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  52599. }
  52600. }
  52601. };
  52602. Sound.prototype.setVolume = function (newVolume, time) {
  52603. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  52604. if (time && BABYLON.Engine.audioEngine.audioContext) {
  52605. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  52606. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  52607. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  52608. }
  52609. else {
  52610. this._soundGain.gain.value = newVolume;
  52611. }
  52612. }
  52613. this._volume = newVolume;
  52614. };
  52615. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  52616. this._playbackRate = newPlaybackRate;
  52617. if (this.isPlaying) {
  52618. if (this._streaming) {
  52619. this._htmlAudioElement.playbackRate = this._playbackRate;
  52620. }
  52621. else if (this._soundSource) {
  52622. this._soundSource.playbackRate.value = this._playbackRate;
  52623. }
  52624. }
  52625. };
  52626. Sound.prototype.getVolume = function () {
  52627. return this._volume;
  52628. };
  52629. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  52630. var _this = this;
  52631. if (this._connectedMesh && this._registerFunc) {
  52632. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52633. this._registerFunc = null;
  52634. }
  52635. this._connectedMesh = meshToConnectTo;
  52636. if (!this.spatialSound) {
  52637. this.spatialSound = true;
  52638. this._createSpatialParameters();
  52639. if (this.isPlaying && this.loop) {
  52640. this.stop();
  52641. this.play();
  52642. }
  52643. }
  52644. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  52645. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  52646. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  52647. };
  52648. Sound.prototype.detachFromMesh = function () {
  52649. if (this._connectedMesh && this._registerFunc) {
  52650. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52651. this._registerFunc = null;
  52652. this._connectedMesh = null;
  52653. }
  52654. };
  52655. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  52656. if (!node.getBoundingInfo) {
  52657. return;
  52658. }
  52659. var mesh = node;
  52660. var boundingInfo = mesh.getBoundingInfo();
  52661. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  52662. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  52663. this._updateDirection();
  52664. }
  52665. };
  52666. Sound.prototype.clone = function () {
  52667. var _this = this;
  52668. if (!this._streaming) {
  52669. var setBufferAndRun = function () {
  52670. if (_this._isReadyToPlay) {
  52671. clonedSound._audioBuffer = _this.getAudioBuffer();
  52672. clonedSound._isReadyToPlay = true;
  52673. if (clonedSound.autoplay) {
  52674. clonedSound.play();
  52675. }
  52676. }
  52677. else {
  52678. window.setTimeout(setBufferAndRun, 300);
  52679. }
  52680. };
  52681. var currentOptions = {
  52682. autoplay: this.autoplay, loop: this.loop,
  52683. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  52684. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  52685. refDistance: this.refDistance, distanceModel: this.distanceModel
  52686. };
  52687. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  52688. if (this.useCustomAttenuation) {
  52689. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  52690. }
  52691. clonedSound.setPosition(this._position);
  52692. clonedSound.setPlaybackRate(this._playbackRate);
  52693. setBufferAndRun();
  52694. return clonedSound;
  52695. }
  52696. else {
  52697. return null;
  52698. }
  52699. };
  52700. Sound.prototype.getAudioBuffer = function () {
  52701. return this._audioBuffer;
  52702. };
  52703. Sound.prototype.serialize = function () {
  52704. var serializationObject = {
  52705. name: this.name,
  52706. url: this.name,
  52707. autoplay: this.autoplay,
  52708. loop: this.loop,
  52709. volume: this._volume,
  52710. spatialSound: this.spatialSound,
  52711. maxDistance: this.maxDistance,
  52712. rolloffFactor: this.rolloffFactor,
  52713. refDistance: this.refDistance,
  52714. distanceModel: this.distanceModel,
  52715. playbackRate: this._playbackRate,
  52716. panningModel: this._panningModel,
  52717. soundTrackId: this.soundTrackId
  52718. };
  52719. if (this.spatialSound) {
  52720. if (this._connectedMesh)
  52721. serializationObject.connectedMeshId = this._connectedMesh.id;
  52722. serializationObject.position = this._position.asArray();
  52723. serializationObject.refDistance = this.refDistance;
  52724. serializationObject.distanceModel = this.distanceModel;
  52725. serializationObject.isDirectional = this._isDirectional;
  52726. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  52727. serializationObject.coneInnerAngle = this._coneInnerAngle;
  52728. serializationObject.coneOuterAngle = this._coneOuterAngle;
  52729. serializationObject.coneOuterGain = this._coneOuterGain;
  52730. }
  52731. return serializationObject;
  52732. };
  52733. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  52734. var soundName = parsedSound.name;
  52735. var soundUrl;
  52736. if (parsedSound.url) {
  52737. soundUrl = rootUrl + parsedSound.url;
  52738. }
  52739. else {
  52740. soundUrl = rootUrl + soundName;
  52741. }
  52742. var options = {
  52743. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  52744. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  52745. rolloffFactor: parsedSound.rolloffFactor,
  52746. refDistance: parsedSound.refDistance,
  52747. distanceModel: parsedSound.distanceModel,
  52748. playbackRate: parsedSound.playbackRate
  52749. };
  52750. var newSound;
  52751. if (!sourceSound) {
  52752. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  52753. scene._addPendingData(newSound);
  52754. }
  52755. else {
  52756. var setBufferAndRun = function () {
  52757. if (sourceSound._isReadyToPlay) {
  52758. newSound._audioBuffer = sourceSound.getAudioBuffer();
  52759. newSound._isReadyToPlay = true;
  52760. if (newSound.autoplay) {
  52761. newSound.play();
  52762. }
  52763. }
  52764. else {
  52765. window.setTimeout(setBufferAndRun, 300);
  52766. }
  52767. };
  52768. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  52769. setBufferAndRun();
  52770. }
  52771. if (parsedSound.position) {
  52772. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  52773. newSound.setPosition(soundPosition);
  52774. }
  52775. if (parsedSound.isDirectional) {
  52776. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  52777. if (parsedSound.localDirectionToMesh) {
  52778. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  52779. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  52780. }
  52781. }
  52782. if (parsedSound.connectedMeshId) {
  52783. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  52784. if (connectedMesh) {
  52785. newSound.attachToMesh(connectedMesh);
  52786. }
  52787. }
  52788. return newSound;
  52789. };
  52790. return Sound;
  52791. }());
  52792. BABYLON.Sound = Sound;
  52793. })(BABYLON || (BABYLON = {}));
  52794. //# sourceMappingURL=babylon.sound.js.map
  52795. var BABYLON;
  52796. (function (BABYLON) {
  52797. var SoundTrack = /** @class */ (function () {
  52798. function SoundTrack(scene, options) {
  52799. this.id = -1;
  52800. this._isMainTrack = false;
  52801. this._isInitialized = false;
  52802. this._scene = scene;
  52803. this.soundCollection = new Array();
  52804. this._options = options;
  52805. if (!this._isMainTrack) {
  52806. this._scene.soundTracks.push(this);
  52807. this.id = this._scene.soundTracks.length - 1;
  52808. }
  52809. }
  52810. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  52811. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52812. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  52813. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  52814. if (this._options) {
  52815. if (this._options.volume) {
  52816. this._outputAudioNode.gain.value = this._options.volume;
  52817. }
  52818. if (this._options.mainTrack) {
  52819. this._isMainTrack = this._options.mainTrack;
  52820. }
  52821. }
  52822. this._isInitialized = true;
  52823. }
  52824. };
  52825. SoundTrack.prototype.dispose = function () {
  52826. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52827. if (this._connectedAnalyser) {
  52828. this._connectedAnalyser.stopDebugCanvas();
  52829. }
  52830. while (this.soundCollection.length) {
  52831. this.soundCollection[0].dispose();
  52832. }
  52833. if (this._outputAudioNode) {
  52834. this._outputAudioNode.disconnect();
  52835. }
  52836. this._outputAudioNode = null;
  52837. }
  52838. };
  52839. SoundTrack.prototype.AddSound = function (sound) {
  52840. if (!this._isInitialized) {
  52841. this._initializeSoundTrackAudioGraph();
  52842. }
  52843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52844. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  52845. }
  52846. if (sound.soundTrackId) {
  52847. if (sound.soundTrackId === -1) {
  52848. this._scene.mainSoundTrack.RemoveSound(sound);
  52849. }
  52850. else {
  52851. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  52852. }
  52853. }
  52854. this.soundCollection.push(sound);
  52855. sound.soundTrackId = this.id;
  52856. };
  52857. SoundTrack.prototype.RemoveSound = function (sound) {
  52858. var index = this.soundCollection.indexOf(sound);
  52859. if (index !== -1) {
  52860. this.soundCollection.splice(index, 1);
  52861. }
  52862. };
  52863. SoundTrack.prototype.setVolume = function (newVolume) {
  52864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52865. this._outputAudioNode.gain.value = newVolume;
  52866. }
  52867. };
  52868. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  52869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52870. for (var i = 0; i < this.soundCollection.length; i++) {
  52871. this.soundCollection[i].switchPanningModelToHRTF();
  52872. }
  52873. }
  52874. };
  52875. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  52876. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52877. for (var i = 0; i < this.soundCollection.length; i++) {
  52878. this.soundCollection[i].switchPanningModelToEqualPower();
  52879. }
  52880. }
  52881. };
  52882. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  52883. if (this._connectedAnalyser) {
  52884. this._connectedAnalyser.stopDebugCanvas();
  52885. }
  52886. this._connectedAnalyser = analyser;
  52887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52888. this._outputAudioNode.disconnect();
  52889. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  52890. }
  52891. };
  52892. return SoundTrack;
  52893. }());
  52894. BABYLON.SoundTrack = SoundTrack;
  52895. })(BABYLON || (BABYLON = {}));
  52896. //# sourceMappingURL=babylon.soundtrack.js.map
  52897. var BABYLON;
  52898. (function (BABYLON) {
  52899. var Analyser = /** @class */ (function () {
  52900. function Analyser(scene) {
  52901. this.SMOOTHING = 0.75;
  52902. this.FFT_SIZE = 512;
  52903. this.BARGRAPHAMPLITUDE = 256;
  52904. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  52905. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  52906. this._scene = scene;
  52907. this._audioEngine = BABYLON.Engine.audioEngine;
  52908. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  52909. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  52910. this._webAudioAnalyser.minDecibels = -140;
  52911. this._webAudioAnalyser.maxDecibels = 0;
  52912. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52913. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52914. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  52915. }
  52916. }
  52917. Analyser.prototype.getFrequencyBinCount = function () {
  52918. if (this._audioEngine.canUseWebAudio) {
  52919. return this._webAudioAnalyser.frequencyBinCount;
  52920. }
  52921. else {
  52922. return 0;
  52923. }
  52924. };
  52925. Analyser.prototype.getByteFrequencyData = function () {
  52926. if (this._audioEngine.canUseWebAudio) {
  52927. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52928. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52929. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  52930. }
  52931. return this._byteFreqs;
  52932. };
  52933. Analyser.prototype.getByteTimeDomainData = function () {
  52934. if (this._audioEngine.canUseWebAudio) {
  52935. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52936. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52937. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  52938. }
  52939. return this._byteTime;
  52940. };
  52941. Analyser.prototype.getFloatFrequencyData = function () {
  52942. if (this._audioEngine.canUseWebAudio) {
  52943. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52944. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52945. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  52946. }
  52947. return this._floatFreqs;
  52948. };
  52949. Analyser.prototype.drawDebugCanvas = function () {
  52950. var _this = this;
  52951. if (this._audioEngine.canUseWebAudio) {
  52952. if (!this._debugCanvas) {
  52953. this._debugCanvas = document.createElement("canvas");
  52954. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  52955. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  52956. this._debugCanvas.style.position = "absolute";
  52957. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  52958. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  52959. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52960. document.body.appendChild(this._debugCanvas);
  52961. this._registerFunc = function () {
  52962. _this.drawDebugCanvas();
  52963. };
  52964. this._scene.registerBeforeRender(this._registerFunc);
  52965. }
  52966. if (this._registerFunc && this._debugCanvasContext) {
  52967. var workingArray = this.getByteFrequencyData();
  52968. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52969. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52970. // Draw the frequency domain chart.
  52971. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52972. var value = workingArray[i];
  52973. var percent = value / this.BARGRAPHAMPLITUDE;
  52974. var height = this.DEBUGCANVASSIZE.height * percent;
  52975. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52976. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52977. var hue = i / this.getFrequencyBinCount() * 360;
  52978. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52979. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52980. }
  52981. }
  52982. }
  52983. };
  52984. Analyser.prototype.stopDebugCanvas = function () {
  52985. if (this._debugCanvas) {
  52986. if (this._registerFunc) {
  52987. this._scene.unregisterBeforeRender(this._registerFunc);
  52988. this._registerFunc = null;
  52989. }
  52990. document.body.removeChild(this._debugCanvas);
  52991. this._debugCanvas = null;
  52992. this._debugCanvasContext = null;
  52993. }
  52994. };
  52995. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52996. if (this._audioEngine.canUseWebAudio) {
  52997. inputAudioNode.connect(this._webAudioAnalyser);
  52998. this._webAudioAnalyser.connect(outputAudioNode);
  52999. }
  53000. };
  53001. Analyser.prototype.dispose = function () {
  53002. if (this._audioEngine.canUseWebAudio) {
  53003. this._webAudioAnalyser.disconnect();
  53004. }
  53005. };
  53006. return Analyser;
  53007. }());
  53008. BABYLON.Analyser = Analyser;
  53009. })(BABYLON || (BABYLON = {}));
  53010. //# sourceMappingURL=babylon.analyser.js.map
  53011. var BABYLON;
  53012. (function (BABYLON) {
  53013. var CubeTexture = /** @class */ (function (_super) {
  53014. __extends(CubeTexture, _super);
  53015. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53016. if (extensions === void 0) { extensions = null; }
  53017. if (noMipmap === void 0) { noMipmap = false; }
  53018. if (files === void 0) { files = null; }
  53019. if (onLoad === void 0) { onLoad = null; }
  53020. if (onError === void 0) { onError = null; }
  53021. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53022. if (prefiltered === void 0) { prefiltered = false; }
  53023. if (forcedExtension === void 0) { forcedExtension = null; }
  53024. var _this = _super.call(this, scene) || this;
  53025. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53026. _this.name = rootUrl;
  53027. _this.url = rootUrl;
  53028. _this._noMipmap = noMipmap;
  53029. _this.hasAlpha = false;
  53030. _this._format = format;
  53031. _this._prefiltered = prefiltered;
  53032. _this.isCube = true;
  53033. _this._textureMatrix = BABYLON.Matrix.Identity();
  53034. if (prefiltered) {
  53035. _this.gammaSpace = false;
  53036. }
  53037. if (!rootUrl && !files) {
  53038. return _this;
  53039. }
  53040. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53041. var lastDot = rootUrl.lastIndexOf(".");
  53042. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53043. var isDDS = (extension === ".dds");
  53044. if (!files) {
  53045. if (!isDDS && !extensions) {
  53046. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53047. }
  53048. files = [];
  53049. if (extensions) {
  53050. for (var index = 0; index < extensions.length; index++) {
  53051. files.push(rootUrl + extensions[index]);
  53052. }
  53053. }
  53054. }
  53055. _this._files = files;
  53056. if (!_this._texture) {
  53057. if (!scene.useDelayedTextureLoading) {
  53058. if (prefiltered) {
  53059. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53060. }
  53061. else {
  53062. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53063. }
  53064. }
  53065. else {
  53066. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53067. }
  53068. }
  53069. else if (onLoad) {
  53070. if (_this._texture.isReady) {
  53071. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53072. }
  53073. else {
  53074. _this._texture.onLoadedObservable.add(onLoad);
  53075. }
  53076. }
  53077. return _this;
  53078. }
  53079. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53080. return new CubeTexture("", scene, null, noMipmap, files);
  53081. };
  53082. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53083. if (forcedExtension === void 0) { forcedExtension = null; }
  53084. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53085. };
  53086. // Methods
  53087. CubeTexture.prototype.delayLoad = function () {
  53088. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53089. return;
  53090. }
  53091. var scene = this.getScene();
  53092. if (!scene) {
  53093. return;
  53094. }
  53095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53096. this._texture = this._getFromCache(this.url, this._noMipmap);
  53097. if (!this._texture) {
  53098. if (this._prefiltered) {
  53099. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53100. }
  53101. else {
  53102. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53103. }
  53104. }
  53105. };
  53106. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53107. return this._textureMatrix;
  53108. };
  53109. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53110. this._textureMatrix = value;
  53111. };
  53112. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53113. var texture = BABYLON.SerializationHelper.Parse(function () {
  53114. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53115. }, parsedTexture, scene);
  53116. // Animations
  53117. if (parsedTexture.animations) {
  53118. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53119. var parsedAnimation = parsedTexture.animations[animationIndex];
  53120. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53121. }
  53122. }
  53123. return texture;
  53124. };
  53125. CubeTexture.prototype.clone = function () {
  53126. var _this = this;
  53127. return BABYLON.SerializationHelper.Clone(function () {
  53128. var scene = _this.getScene();
  53129. if (!scene) {
  53130. return _this;
  53131. }
  53132. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53133. }, this);
  53134. };
  53135. return CubeTexture;
  53136. }(BABYLON.BaseTexture));
  53137. BABYLON.CubeTexture = CubeTexture;
  53138. })(BABYLON || (BABYLON = {}));
  53139. //# sourceMappingURL=babylon.cubeTexture.js.map
  53140. var BABYLON;
  53141. (function (BABYLON) {
  53142. var RenderTargetTexture = /** @class */ (function (_super) {
  53143. __extends(RenderTargetTexture, _super);
  53144. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53145. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53146. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53147. if (isCube === void 0) { isCube = false; }
  53148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53149. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53150. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53151. if (isMulti === void 0) { isMulti = false; }
  53152. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53153. _this.isCube = isCube;
  53154. /**
  53155. * Use this list to define the list of mesh you want to render.
  53156. */
  53157. _this.renderList = new Array();
  53158. _this.renderParticles = true;
  53159. _this.renderSprites = false;
  53160. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53161. _this.ignoreCameraViewport = false;
  53162. // Events
  53163. /**
  53164. * An event triggered when the texture is unbind.
  53165. * @type {BABYLON.Observable}
  53166. */
  53167. _this.onBeforeBindObservable = new BABYLON.Observable();
  53168. /**
  53169. * An event triggered when the texture is unbind.
  53170. * @type {BABYLON.Observable}
  53171. */
  53172. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53173. /**
  53174. * An event triggered before rendering the texture
  53175. * @type {BABYLON.Observable}
  53176. */
  53177. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53178. /**
  53179. * An event triggered after rendering the texture
  53180. * @type {BABYLON.Observable}
  53181. */
  53182. _this.onAfterRenderObservable = new BABYLON.Observable();
  53183. /**
  53184. * An event triggered after the texture clear
  53185. * @type {BABYLON.Observable}
  53186. */
  53187. _this.onClearObservable = new BABYLON.Observable();
  53188. _this._currentRefreshId = -1;
  53189. _this._refreshRate = 1;
  53190. _this._samples = 1;
  53191. scene = _this.getScene();
  53192. if (!scene) {
  53193. return _this;
  53194. }
  53195. _this._engine = scene.getEngine();
  53196. _this.name = name;
  53197. _this.isRenderTarget = true;
  53198. _this._initialSizeParameter = size;
  53199. _this._processSizeParameter(size);
  53200. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53201. });
  53202. _this._generateMipMaps = generateMipMaps ? true : false;
  53203. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53204. // Rendering groups
  53205. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53206. if (isMulti) {
  53207. return _this;
  53208. }
  53209. _this._renderTargetOptions = {
  53210. generateMipMaps: generateMipMaps,
  53211. type: type,
  53212. samplingMode: samplingMode,
  53213. generateDepthBuffer: generateDepthBuffer,
  53214. generateStencilBuffer: generateStencilBuffer
  53215. };
  53216. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53217. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53218. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53219. }
  53220. if (isCube) {
  53221. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53222. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53223. _this._textureMatrix = BABYLON.Matrix.Identity();
  53224. }
  53225. else {
  53226. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53227. }
  53228. return _this;
  53229. }
  53230. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53231. get: function () {
  53232. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53238. get: function () {
  53239. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53240. },
  53241. enumerable: true,
  53242. configurable: true
  53243. });
  53244. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53245. get: function () {
  53246. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53247. },
  53248. enumerable: true,
  53249. configurable: true
  53250. });
  53251. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53252. set: function (callback) {
  53253. if (this._onAfterUnbindObserver) {
  53254. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53255. }
  53256. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53257. },
  53258. enumerable: true,
  53259. configurable: true
  53260. });
  53261. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53262. set: function (callback) {
  53263. if (this._onBeforeRenderObserver) {
  53264. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53265. }
  53266. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53267. },
  53268. enumerable: true,
  53269. configurable: true
  53270. });
  53271. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53272. set: function (callback) {
  53273. if (this._onAfterRenderObserver) {
  53274. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53275. }
  53276. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53277. },
  53278. enumerable: true,
  53279. configurable: true
  53280. });
  53281. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53282. set: function (callback) {
  53283. if (this._onClearObserver) {
  53284. this.onClearObservable.remove(this._onClearObserver);
  53285. }
  53286. this._onClearObserver = this.onClearObservable.add(callback);
  53287. },
  53288. enumerable: true,
  53289. configurable: true
  53290. });
  53291. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53292. get: function () {
  53293. return this._renderTargetOptions;
  53294. },
  53295. enumerable: true,
  53296. configurable: true
  53297. });
  53298. RenderTargetTexture.prototype._onRatioRescale = function () {
  53299. if (this._sizeRatio) {
  53300. this.resize(this._initialSizeParameter);
  53301. }
  53302. };
  53303. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53304. if (size.ratio) {
  53305. this._sizeRatio = size.ratio;
  53306. this._size = {
  53307. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53308. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53309. };
  53310. }
  53311. else {
  53312. this._size = size;
  53313. }
  53314. };
  53315. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53316. get: function () {
  53317. return this._samples;
  53318. },
  53319. set: function (value) {
  53320. if (this._samples === value) {
  53321. return;
  53322. }
  53323. var scene = this.getScene();
  53324. if (!scene) {
  53325. return;
  53326. }
  53327. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53333. this._currentRefreshId = -1;
  53334. };
  53335. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53336. get: function () {
  53337. return this._refreshRate;
  53338. },
  53339. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53340. set: function (value) {
  53341. this._refreshRate = value;
  53342. this.resetRefreshCounter();
  53343. },
  53344. enumerable: true,
  53345. configurable: true
  53346. });
  53347. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53348. if (!this._postProcessManager) {
  53349. var scene = this.getScene();
  53350. if (!scene) {
  53351. return;
  53352. }
  53353. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53354. this._postProcesses = new Array();
  53355. }
  53356. this._postProcesses.push(postProcess);
  53357. this._postProcesses[0].autoClear = false;
  53358. };
  53359. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53360. if (!this._postProcesses) {
  53361. return;
  53362. }
  53363. if (dispose) {
  53364. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53365. var postProcess = _a[_i];
  53366. postProcess.dispose();
  53367. }
  53368. }
  53369. this._postProcesses = [];
  53370. };
  53371. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53372. if (!this._postProcesses) {
  53373. return;
  53374. }
  53375. var index = this._postProcesses.indexOf(postProcess);
  53376. if (index === -1) {
  53377. return;
  53378. }
  53379. this._postProcesses.splice(index, 1);
  53380. if (this._postProcesses.length > 0) {
  53381. this._postProcesses[0].autoClear = false;
  53382. }
  53383. };
  53384. RenderTargetTexture.prototype._shouldRender = function () {
  53385. if (this._currentRefreshId === -1) {
  53386. this._currentRefreshId = 1;
  53387. return true;
  53388. }
  53389. if (this.refreshRate === this._currentRefreshId) {
  53390. this._currentRefreshId = 1;
  53391. return true;
  53392. }
  53393. this._currentRefreshId++;
  53394. return false;
  53395. };
  53396. RenderTargetTexture.prototype.getRenderSize = function () {
  53397. if (this._size.width) {
  53398. return this._size.width;
  53399. }
  53400. return this._size;
  53401. };
  53402. RenderTargetTexture.prototype.getRenderWidth = function () {
  53403. if (this._size.width) {
  53404. return this._size.width;
  53405. }
  53406. return this._size;
  53407. };
  53408. RenderTargetTexture.prototype.getRenderHeight = function () {
  53409. if (this._size.width) {
  53410. return this._size.height;
  53411. }
  53412. return this._size;
  53413. };
  53414. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53415. get: function () {
  53416. return true;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. RenderTargetTexture.prototype.scale = function (ratio) {
  53422. var newSize = this.getRenderSize() * ratio;
  53423. this.resize(newSize);
  53424. };
  53425. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53426. if (this.isCube) {
  53427. return this._textureMatrix;
  53428. }
  53429. return _super.prototype.getReflectionTextureMatrix.call(this);
  53430. };
  53431. RenderTargetTexture.prototype.resize = function (size) {
  53432. this.releaseInternalTexture();
  53433. var scene = this.getScene();
  53434. if (!scene) {
  53435. return;
  53436. }
  53437. this._processSizeParameter(size);
  53438. if (this.isCube) {
  53439. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53440. }
  53441. else {
  53442. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53443. }
  53444. };
  53445. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53446. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53447. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53448. var scene = this.getScene();
  53449. if (!scene) {
  53450. return;
  53451. }
  53452. var engine = scene.getEngine();
  53453. if (this.useCameraPostProcesses !== undefined) {
  53454. useCameraPostProcess = this.useCameraPostProcesses;
  53455. }
  53456. if (this._waitingRenderList) {
  53457. this.renderList = [];
  53458. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53459. var id = this._waitingRenderList[index];
  53460. var mesh_1 = scene.getMeshByID(id);
  53461. if (mesh_1) {
  53462. this.renderList.push(mesh_1);
  53463. }
  53464. }
  53465. delete this._waitingRenderList;
  53466. }
  53467. // Is predicate defined?
  53468. if (this.renderListPredicate) {
  53469. if (this.renderList) {
  53470. this.renderList.splice(0); // Clear previous renderList
  53471. }
  53472. else {
  53473. this.renderList = [];
  53474. }
  53475. var scene = this.getScene();
  53476. if (!scene) {
  53477. return;
  53478. }
  53479. var sceneMeshes = scene.meshes;
  53480. for (var index = 0; index < sceneMeshes.length; index++) {
  53481. var mesh = sceneMeshes[index];
  53482. if (this.renderListPredicate(mesh)) {
  53483. this.renderList.push(mesh);
  53484. }
  53485. }
  53486. }
  53487. this.onBeforeBindObservable.notifyObservers(this);
  53488. // Set custom projection.
  53489. // Needs to be before binding to prevent changing the aspect ratio.
  53490. var camera;
  53491. if (this.activeCamera) {
  53492. camera = this.activeCamera;
  53493. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53494. if (this.activeCamera !== scene.activeCamera) {
  53495. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  53496. }
  53497. }
  53498. else {
  53499. camera = scene.activeCamera;
  53500. if (camera) {
  53501. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53502. }
  53503. }
  53504. // Prepare renderingManager
  53505. this._renderingManager.reset();
  53506. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  53507. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  53508. var sceneRenderId = scene.getRenderId();
  53509. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  53510. var mesh = currentRenderList[meshIndex];
  53511. if (mesh) {
  53512. if (!mesh.isReady()) {
  53513. // Reset _currentRefreshId
  53514. this.resetRefreshCounter();
  53515. continue;
  53516. }
  53517. mesh._preActivateForIntermediateRendering(sceneRenderId);
  53518. var isMasked = void 0;
  53519. if (!this.renderList && camera) {
  53520. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  53521. }
  53522. else {
  53523. isMasked = false;
  53524. }
  53525. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  53526. mesh._activate(sceneRenderId);
  53527. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  53528. var subMesh = mesh.subMeshes[subIndex];
  53529. scene._activeIndices.addCount(subMesh.indexCount, false);
  53530. this._renderingManager.dispatch(subMesh, mesh);
  53531. }
  53532. }
  53533. }
  53534. }
  53535. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  53536. var particleSystem = scene.particleSystems[particleIndex];
  53537. var emitter = particleSystem.emitter;
  53538. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  53539. continue;
  53540. }
  53541. if (currentRenderList.indexOf(emitter) >= 0) {
  53542. this._renderingManager.dispatchParticles(particleSystem);
  53543. }
  53544. }
  53545. if (this.isCube) {
  53546. for (var face = 0; face < 6; face++) {
  53547. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53548. scene.incrementRenderId();
  53549. scene.resetCachedMaterial();
  53550. }
  53551. }
  53552. else {
  53553. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53554. }
  53555. this.onAfterUnbindObservable.notifyObservers(this);
  53556. if (scene.activeCamera) {
  53557. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  53558. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  53559. }
  53560. engine.setViewport(scene.activeCamera.viewport);
  53561. }
  53562. scene.resetCachedMaterial();
  53563. };
  53564. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  53565. var minimum = 128;
  53566. var x = renderDimension * scale;
  53567. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  53568. // Ensure we don't exceed the render dimension (while staying POT)
  53569. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  53570. };
  53571. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53572. var _this = this;
  53573. if (!this._texture) {
  53574. return;
  53575. }
  53576. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  53577. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53578. });
  53579. };
  53580. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  53581. var scene = this.getScene();
  53582. if (!scene) {
  53583. return;
  53584. }
  53585. var engine = scene.getEngine();
  53586. if (!this._texture) {
  53587. return;
  53588. }
  53589. // Bind
  53590. if (this._postProcessManager) {
  53591. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  53592. }
  53593. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  53594. if (this._texture) {
  53595. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  53596. }
  53597. }
  53598. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  53599. // Clear
  53600. if (this.onClearObservable.hasObservers()) {
  53601. this.onClearObservable.notifyObservers(engine);
  53602. }
  53603. else {
  53604. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  53605. }
  53606. if (!this._doNotChangeAspectRatio) {
  53607. scene.updateTransformMatrix(true);
  53608. }
  53609. // Render
  53610. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  53611. if (this._postProcessManager) {
  53612. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  53613. }
  53614. else if (useCameraPostProcess) {
  53615. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  53616. }
  53617. if (!this._doNotChangeAspectRatio) {
  53618. scene.updateTransformMatrix(true);
  53619. }
  53620. // Dump ?
  53621. if (dumpForDebug) {
  53622. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  53623. }
  53624. // Unbind
  53625. if (!this.isCube || faceIndex === 5) {
  53626. if (this.isCube) {
  53627. if (faceIndex === 5) {
  53628. engine.generateMipMapsForCubemap(this._texture);
  53629. }
  53630. }
  53631. this.unbindFrameBuffer(engine, faceIndex);
  53632. }
  53633. else {
  53634. this.onAfterRenderObservable.notifyObservers(faceIndex);
  53635. }
  53636. };
  53637. /**
  53638. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  53639. * This allowed control for front to back rendering or reversly depending of the special needs.
  53640. *
  53641. * @param renderingGroupId The rendering group id corresponding to its index
  53642. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  53643. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  53644. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  53645. */
  53646. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  53647. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  53648. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  53649. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  53650. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  53651. };
  53652. /**
  53653. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  53654. *
  53655. * @param renderingGroupId The rendering group id corresponding to its index
  53656. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  53657. */
  53658. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  53659. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  53660. };
  53661. RenderTargetTexture.prototype.clone = function () {
  53662. var textureSize = this.getSize();
  53663. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  53664. // Base texture
  53665. newTexture.hasAlpha = this.hasAlpha;
  53666. newTexture.level = this.level;
  53667. // RenderTarget Texture
  53668. newTexture.coordinatesMode = this.coordinatesMode;
  53669. if (this.renderList) {
  53670. newTexture.renderList = this.renderList.slice(0);
  53671. }
  53672. return newTexture;
  53673. };
  53674. RenderTargetTexture.prototype.serialize = function () {
  53675. if (!this.name) {
  53676. return null;
  53677. }
  53678. var serializationObject = _super.prototype.serialize.call(this);
  53679. serializationObject.renderTargetSize = this.getRenderSize();
  53680. serializationObject.renderList = [];
  53681. if (this.renderList) {
  53682. for (var index = 0; index < this.renderList.length; index++) {
  53683. serializationObject.renderList.push(this.renderList[index].id);
  53684. }
  53685. }
  53686. return serializationObject;
  53687. };
  53688. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  53689. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  53690. var objBuffer = this.getInternalTexture();
  53691. var scene = this.getScene();
  53692. if (objBuffer && scene) {
  53693. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  53694. }
  53695. };
  53696. RenderTargetTexture.prototype.dispose = function () {
  53697. if (this._postProcessManager) {
  53698. this._postProcessManager.dispose();
  53699. this._postProcessManager = null;
  53700. }
  53701. this.clearPostProcesses(true);
  53702. if (this._resizeObserver) {
  53703. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  53704. this._resizeObserver = null;
  53705. }
  53706. this.renderList = null;
  53707. // Remove from custom render targets
  53708. var scene = this.getScene();
  53709. if (!scene) {
  53710. return;
  53711. }
  53712. var index = scene.customRenderTargets.indexOf(this);
  53713. if (index >= 0) {
  53714. scene.customRenderTargets.splice(index, 1);
  53715. }
  53716. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  53717. var camera = _a[_i];
  53718. index = camera.customRenderTargets.indexOf(this);
  53719. if (index >= 0) {
  53720. camera.customRenderTargets.splice(index, 1);
  53721. }
  53722. }
  53723. _super.prototype.dispose.call(this);
  53724. };
  53725. RenderTargetTexture.prototype._rebuild = function () {
  53726. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53727. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53728. }
  53729. if (this._postProcessManager) {
  53730. this._postProcessManager._rebuild();
  53731. }
  53732. };
  53733. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  53734. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  53735. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  53736. return RenderTargetTexture;
  53737. }(BABYLON.Texture));
  53738. BABYLON.RenderTargetTexture = RenderTargetTexture;
  53739. })(BABYLON || (BABYLON = {}));
  53740. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  53741. var BABYLON;
  53742. (function (BABYLON) {
  53743. ;
  53744. var MultiRenderTarget = /** @class */ (function (_super) {
  53745. __extends(MultiRenderTarget, _super);
  53746. function MultiRenderTarget(name, size, count, scene, options) {
  53747. var _this = this;
  53748. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  53749. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  53750. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  53751. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  53752. _this._engine = scene.getEngine();
  53753. if (!_this.isSupported) {
  53754. _this.dispose();
  53755. return;
  53756. }
  53757. var types = [];
  53758. var samplingModes = [];
  53759. for (var i = 0; i < count; i++) {
  53760. if (options && options.types && options.types[i] !== undefined) {
  53761. types.push(options.types[i]);
  53762. }
  53763. else {
  53764. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53765. }
  53766. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  53767. samplingModes.push(options.samplingModes[i]);
  53768. }
  53769. else {
  53770. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53771. }
  53772. }
  53773. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  53774. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  53775. _this._size = size;
  53776. _this._multiRenderTargetOptions = {
  53777. samplingModes: samplingModes,
  53778. generateMipMaps: generateMipMaps,
  53779. generateDepthBuffer: generateDepthBuffer,
  53780. generateStencilBuffer: generateStencilBuffer,
  53781. generateDepthTexture: generateDepthTexture,
  53782. types: types,
  53783. textureCount: count
  53784. };
  53785. _this._createInternalTextures();
  53786. _this._createTextures();
  53787. return _this;
  53788. }
  53789. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  53790. get: function () {
  53791. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  53792. },
  53793. enumerable: true,
  53794. configurable: true
  53795. });
  53796. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  53797. get: function () {
  53798. return this._textures;
  53799. },
  53800. enumerable: true,
  53801. configurable: true
  53802. });
  53803. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  53804. get: function () {
  53805. return this._textures[this._textures.length - 1];
  53806. },
  53807. enumerable: true,
  53808. configurable: true
  53809. });
  53810. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  53811. set: function (wrap) {
  53812. if (this._textures) {
  53813. for (var i = 0; i < this._textures.length; i++) {
  53814. this._textures[i].wrapU = wrap;
  53815. }
  53816. }
  53817. },
  53818. enumerable: true,
  53819. configurable: true
  53820. });
  53821. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  53822. set: function (wrap) {
  53823. if (this._textures) {
  53824. for (var i = 0; i < this._textures.length; i++) {
  53825. this._textures[i].wrapV = wrap;
  53826. }
  53827. }
  53828. },
  53829. enumerable: true,
  53830. configurable: true
  53831. });
  53832. MultiRenderTarget.prototype._rebuild = function () {
  53833. this.releaseInternalTextures();
  53834. this._createInternalTextures();
  53835. for (var i = 0; i < this._internalTextures.length; i++) {
  53836. var texture = this._textures[i];
  53837. texture._texture = this._internalTextures[i];
  53838. }
  53839. // Keeps references to frame buffer and stencil/depth buffer
  53840. this._texture = this._internalTextures[0];
  53841. };
  53842. MultiRenderTarget.prototype._createInternalTextures = function () {
  53843. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  53844. };
  53845. MultiRenderTarget.prototype._createTextures = function () {
  53846. this._textures = [];
  53847. for (var i = 0; i < this._internalTextures.length; i++) {
  53848. var texture = new BABYLON.Texture(null, this.getScene());
  53849. texture._texture = this._internalTextures[i];
  53850. this._textures.push(texture);
  53851. }
  53852. // Keeps references to frame buffer and stencil/depth buffer
  53853. this._texture = this._internalTextures[0];
  53854. };
  53855. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  53856. get: function () {
  53857. return this._samples;
  53858. },
  53859. set: function (value) {
  53860. if (this._samples === value) {
  53861. return;
  53862. }
  53863. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  53864. },
  53865. enumerable: true,
  53866. configurable: true
  53867. });
  53868. MultiRenderTarget.prototype.resize = function (size) {
  53869. this.releaseInternalTextures();
  53870. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  53871. this._createInternalTextures();
  53872. };
  53873. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53874. var _this = this;
  53875. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  53876. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53877. });
  53878. };
  53879. MultiRenderTarget.prototype.dispose = function () {
  53880. this.releaseInternalTextures();
  53881. _super.prototype.dispose.call(this);
  53882. };
  53883. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  53884. if (!this._internalTextures) {
  53885. return;
  53886. }
  53887. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  53888. if (this._internalTextures[i] !== undefined) {
  53889. this._internalTextures[i].dispose();
  53890. this._internalTextures.splice(i, 1);
  53891. }
  53892. }
  53893. };
  53894. return MultiRenderTarget;
  53895. }(BABYLON.RenderTargetTexture));
  53896. BABYLON.MultiRenderTarget = MultiRenderTarget;
  53897. })(BABYLON || (BABYLON = {}));
  53898. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  53899. var BABYLON;
  53900. (function (BABYLON) {
  53901. var MirrorTexture = /** @class */ (function (_super) {
  53902. __extends(MirrorTexture, _super);
  53903. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  53904. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53906. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53907. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  53908. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  53909. _this._transformMatrix = BABYLON.Matrix.Zero();
  53910. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  53911. _this._adaptiveBlurKernel = 0;
  53912. _this._blurKernelX = 0;
  53913. _this._blurKernelY = 0;
  53914. _this._blurRatio = 1.0;
  53915. _this.ignoreCameraViewport = true;
  53916. _this.onBeforeRenderObservable.add(function () {
  53917. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  53918. _this._savedViewMatrix = scene.getViewMatrix();
  53919. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  53920. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  53921. scene.clipPlane = _this.mirrorPlane;
  53922. scene.getEngine().cullBackFaces = false;
  53923. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  53924. });
  53925. _this.onAfterRenderObservable.add(function () {
  53926. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  53927. scene.getEngine().cullBackFaces = true;
  53928. scene._mirroredCameraPosition = null;
  53929. delete scene.clipPlane;
  53930. });
  53931. return _this;
  53932. }
  53933. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  53934. get: function () {
  53935. return this._blurRatio;
  53936. },
  53937. set: function (value) {
  53938. if (this._blurRatio === value) {
  53939. return;
  53940. }
  53941. this._blurRatio = value;
  53942. this._preparePostProcesses();
  53943. },
  53944. enumerable: true,
  53945. configurable: true
  53946. });
  53947. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  53948. set: function (value) {
  53949. this._adaptiveBlurKernel = value;
  53950. this._autoComputeBlurKernel();
  53951. },
  53952. enumerable: true,
  53953. configurable: true
  53954. });
  53955. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  53956. set: function (value) {
  53957. this.blurKernelX = value;
  53958. this.blurKernelY = value;
  53959. },
  53960. enumerable: true,
  53961. configurable: true
  53962. });
  53963. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  53964. get: function () {
  53965. return this._blurKernelX;
  53966. },
  53967. set: function (value) {
  53968. if (this._blurKernelX === value) {
  53969. return;
  53970. }
  53971. this._blurKernelX = value;
  53972. this._preparePostProcesses();
  53973. },
  53974. enumerable: true,
  53975. configurable: true
  53976. });
  53977. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  53978. get: function () {
  53979. return this._blurKernelY;
  53980. },
  53981. set: function (value) {
  53982. if (this._blurKernelY === value) {
  53983. return;
  53984. }
  53985. this._blurKernelY = value;
  53986. this._preparePostProcesses();
  53987. },
  53988. enumerable: true,
  53989. configurable: true
  53990. });
  53991. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  53992. var engine = this.getScene().getEngine();
  53993. var dw = this.getRenderWidth() / engine.getRenderWidth();
  53994. var dh = this.getRenderHeight() / engine.getRenderHeight();
  53995. this.blurKernelX = this._adaptiveBlurKernel * dw;
  53996. this.blurKernelY = this._adaptiveBlurKernel * dh;
  53997. };
  53998. MirrorTexture.prototype._onRatioRescale = function () {
  53999. if (this._sizeRatio) {
  54000. this.resize(this._initialSizeParameter);
  54001. if (!this._adaptiveBlurKernel) {
  54002. this._preparePostProcesses();
  54003. }
  54004. }
  54005. if (this._adaptiveBlurKernel) {
  54006. this._autoComputeBlurKernel();
  54007. }
  54008. };
  54009. MirrorTexture.prototype._preparePostProcesses = function () {
  54010. this.clearPostProcesses(true);
  54011. if (this._blurKernelX && this._blurKernelY) {
  54012. var engine = this.getScene().getEngine();
  54013. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54014. 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);
  54015. this._blurX.autoClear = false;
  54016. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54017. this._blurX.outputTexture = this._texture;
  54018. }
  54019. else {
  54020. this._blurX.alwaysForcePOT = true;
  54021. }
  54022. 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);
  54023. this._blurY.autoClear = false;
  54024. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54025. this.addPostProcess(this._blurX);
  54026. this.addPostProcess(this._blurY);
  54027. }
  54028. else {
  54029. if (this._blurY) {
  54030. this.removePostProcess(this._blurY);
  54031. this._blurY.dispose();
  54032. this._blurY = null;
  54033. }
  54034. if (this._blurX) {
  54035. this.removePostProcess(this._blurX);
  54036. this._blurX.dispose();
  54037. this._blurX = null;
  54038. }
  54039. }
  54040. };
  54041. MirrorTexture.prototype.clone = function () {
  54042. var scene = this.getScene();
  54043. if (!scene) {
  54044. return this;
  54045. }
  54046. var textureSize = this.getSize();
  54047. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54048. // Base texture
  54049. newTexture.hasAlpha = this.hasAlpha;
  54050. newTexture.level = this.level;
  54051. // Mirror Texture
  54052. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54053. if (this.renderList) {
  54054. newTexture.renderList = this.renderList.slice(0);
  54055. }
  54056. return newTexture;
  54057. };
  54058. MirrorTexture.prototype.serialize = function () {
  54059. if (!this.name) {
  54060. return null;
  54061. }
  54062. var serializationObject = _super.prototype.serialize.call(this);
  54063. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54064. return serializationObject;
  54065. };
  54066. return MirrorTexture;
  54067. }(BABYLON.RenderTargetTexture));
  54068. BABYLON.MirrorTexture = MirrorTexture;
  54069. })(BABYLON || (BABYLON = {}));
  54070. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54071. var BABYLON;
  54072. (function (BABYLON) {
  54073. /**
  54074. * Creates a refraction texture used by refraction channel of the standard material.
  54075. * @param name the texture name
  54076. * @param size size of the underlying texture
  54077. * @param scene root scene
  54078. */
  54079. var RefractionTexture = /** @class */ (function (_super) {
  54080. __extends(RefractionTexture, _super);
  54081. function RefractionTexture(name, size, scene, generateMipMaps) {
  54082. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54083. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54084. _this.depth = 2.0;
  54085. _this.onBeforeRenderObservable.add(function () {
  54086. scene.clipPlane = _this.refractionPlane;
  54087. });
  54088. _this.onAfterRenderObservable.add(function () {
  54089. delete scene.clipPlane;
  54090. });
  54091. return _this;
  54092. }
  54093. RefractionTexture.prototype.clone = function () {
  54094. var scene = this.getScene();
  54095. if (!scene) {
  54096. return this;
  54097. }
  54098. var textureSize = this.getSize();
  54099. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54100. // Base texture
  54101. newTexture.hasAlpha = this.hasAlpha;
  54102. newTexture.level = this.level;
  54103. // Refraction Texture
  54104. newTexture.refractionPlane = this.refractionPlane.clone();
  54105. if (this.renderList) {
  54106. newTexture.renderList = this.renderList.slice(0);
  54107. }
  54108. newTexture.depth = this.depth;
  54109. return newTexture;
  54110. };
  54111. RefractionTexture.prototype.serialize = function () {
  54112. if (!this.name) {
  54113. return null;
  54114. }
  54115. var serializationObject = _super.prototype.serialize.call(this);
  54116. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54117. serializationObject.depth = this.depth;
  54118. return serializationObject;
  54119. };
  54120. return RefractionTexture;
  54121. }(BABYLON.RenderTargetTexture));
  54122. BABYLON.RefractionTexture = RefractionTexture;
  54123. })(BABYLON || (BABYLON = {}));
  54124. //# sourceMappingURL=babylon.refractionTexture.js.map
  54125. var BABYLON;
  54126. (function (BABYLON) {
  54127. var DynamicTexture = /** @class */ (function (_super) {
  54128. __extends(DynamicTexture, _super);
  54129. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54130. if (scene === void 0) { scene = null; }
  54131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54132. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54133. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54134. _this.name = name;
  54135. _this._engine = _this.getScene().getEngine();
  54136. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54137. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54138. _this._generateMipMaps = generateMipMaps;
  54139. if (options.getContext) {
  54140. _this._canvas = options;
  54141. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54142. }
  54143. else {
  54144. _this._canvas = document.createElement("canvas");
  54145. if (options.width) {
  54146. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54147. }
  54148. else {
  54149. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54150. }
  54151. }
  54152. var textureSize = _this.getSize();
  54153. _this._canvas.width = textureSize.width;
  54154. _this._canvas.height = textureSize.height;
  54155. _this._context = _this._canvas.getContext("2d");
  54156. return _this;
  54157. }
  54158. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54159. get: function () {
  54160. return true;
  54161. },
  54162. enumerable: true,
  54163. configurable: true
  54164. });
  54165. DynamicTexture.prototype._recreate = function (textureSize) {
  54166. this._canvas.width = textureSize.width;
  54167. this._canvas.height = textureSize.height;
  54168. this.releaseInternalTexture();
  54169. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54170. };
  54171. DynamicTexture.prototype.scale = function (ratio) {
  54172. var textureSize = this.getSize();
  54173. textureSize.width *= ratio;
  54174. textureSize.height *= ratio;
  54175. this._recreate(textureSize);
  54176. };
  54177. DynamicTexture.prototype.scaleTo = function (width, height) {
  54178. var textureSize = this.getSize();
  54179. textureSize.width = width;
  54180. textureSize.height = height;
  54181. this._recreate(textureSize);
  54182. };
  54183. DynamicTexture.prototype.getContext = function () {
  54184. return this._context;
  54185. };
  54186. DynamicTexture.prototype.clear = function () {
  54187. var size = this.getSize();
  54188. this._context.fillRect(0, 0, size.width, size.height);
  54189. };
  54190. DynamicTexture.prototype.update = function (invertY) {
  54191. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54192. };
  54193. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54194. if (update === void 0) { update = true; }
  54195. var size = this.getSize();
  54196. if (clearColor) {
  54197. this._context.fillStyle = clearColor;
  54198. this._context.fillRect(0, 0, size.width, size.height);
  54199. }
  54200. this._context.font = font;
  54201. if (x === null || x === undefined) {
  54202. var textSize = this._context.measureText(text);
  54203. x = (size.width - textSize.width) / 2;
  54204. }
  54205. if (y === null || y === undefined) {
  54206. var fontSize = parseInt((font.replace(/\D/g, '')));
  54207. ;
  54208. y = (size.height / 2) + (fontSize / 3.65);
  54209. }
  54210. this._context.fillStyle = color;
  54211. this._context.fillText(text, x, y);
  54212. if (update) {
  54213. this.update(invertY);
  54214. }
  54215. };
  54216. DynamicTexture.prototype.clone = function () {
  54217. var scene = this.getScene();
  54218. if (!scene) {
  54219. return this;
  54220. }
  54221. var textureSize = this.getSize();
  54222. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54223. // Base texture
  54224. newTexture.hasAlpha = this.hasAlpha;
  54225. newTexture.level = this.level;
  54226. // Dynamic Texture
  54227. newTexture.wrapU = this.wrapU;
  54228. newTexture.wrapV = this.wrapV;
  54229. return newTexture;
  54230. };
  54231. DynamicTexture.prototype._rebuild = function () {
  54232. this.update();
  54233. };
  54234. return DynamicTexture;
  54235. }(BABYLON.Texture));
  54236. BABYLON.DynamicTexture = DynamicTexture;
  54237. })(BABYLON || (BABYLON = {}));
  54238. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54239. var BABYLON;
  54240. (function (BABYLON) {
  54241. var VideoTexture = /** @class */ (function (_super) {
  54242. __extends(VideoTexture, _super);
  54243. /**
  54244. * Creates a video texture.
  54245. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54246. * @param {string | null} name optional name, will detect from video source, if not defined
  54247. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54248. * @param {BABYLON.Scene} scene is obviously the current scene.
  54249. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54250. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54251. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54252. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54253. */
  54254. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54255. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54256. if (invertY === void 0) { invertY = false; }
  54257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54258. if (settings === void 0) { settings = {
  54259. autoPlay: true,
  54260. loop: true,
  54261. autoUpdateTexture: true,
  54262. }; }
  54263. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54264. _this._createInternalTexture = function () {
  54265. if (_this._texture != null) {
  54266. return;
  54267. }
  54268. if (!_this._engine.needPOTTextures ||
  54269. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54270. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54271. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54272. }
  54273. else {
  54274. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54275. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54276. _this._generateMipMaps = false;
  54277. }
  54278. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54279. _this._texture.width;
  54280. _this._updateInternalTexture();
  54281. _this._texture.isReady = true;
  54282. };
  54283. _this.reset = function () {
  54284. if (_this._texture == null) {
  54285. return;
  54286. }
  54287. _this._texture.dispose();
  54288. _this._texture = null;
  54289. };
  54290. _this._updateInternalTexture = function (e) {
  54291. if (_this._texture == null || !_this._texture.isReady) {
  54292. return;
  54293. }
  54294. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54295. return;
  54296. }
  54297. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54298. };
  54299. _this._engine = _this.getScene().getEngine();
  54300. _this._generateMipMaps = generateMipMaps;
  54301. _this._samplingMode = samplingMode;
  54302. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54303. _this.name = name || _this._getName(src);
  54304. _this.video = _this._getVideo(src);
  54305. if (settings.autoPlay !== undefined) {
  54306. _this.video.autoplay = settings.autoPlay;
  54307. }
  54308. if (settings.loop !== undefined) {
  54309. _this.video.loop = settings.loop;
  54310. }
  54311. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54312. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54313. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54314. _this.video.addEventListener("emptied", _this.reset);
  54315. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54316. _this._createInternalTexture();
  54317. }
  54318. return _this;
  54319. }
  54320. VideoTexture.prototype._getName = function (src) {
  54321. if (src instanceof HTMLVideoElement) {
  54322. return src.currentSrc;
  54323. }
  54324. if (typeof src === "object") {
  54325. return src.toString();
  54326. }
  54327. return src;
  54328. };
  54329. ;
  54330. VideoTexture.prototype._getVideo = function (src) {
  54331. if (src instanceof HTMLVideoElement) {
  54332. return src;
  54333. }
  54334. var video = document.createElement("video");
  54335. if (typeof src === "string") {
  54336. video.src = src;
  54337. }
  54338. else {
  54339. src.forEach(function (url) {
  54340. var source = document.createElement("source");
  54341. source.src = url;
  54342. video.appendChild(source);
  54343. });
  54344. }
  54345. return video;
  54346. };
  54347. ;
  54348. /**
  54349. * Internal method to initiate `update`.
  54350. */
  54351. VideoTexture.prototype._rebuild = function () {
  54352. this.update();
  54353. };
  54354. /**
  54355. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54356. */
  54357. VideoTexture.prototype.update = function () {
  54358. if (!this.autoUpdateTexture) {
  54359. // Expecting user to call `updateTexture` manually
  54360. return;
  54361. }
  54362. this.updateTexture(true);
  54363. };
  54364. /**
  54365. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54366. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54367. */
  54368. VideoTexture.prototype.updateTexture = function (isVisible) {
  54369. if (!isVisible) {
  54370. return;
  54371. }
  54372. if (this.video.paused) {
  54373. return;
  54374. }
  54375. this._updateInternalTexture();
  54376. };
  54377. /**
  54378. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54379. * @param url New url.
  54380. */
  54381. VideoTexture.prototype.updateURL = function (url) {
  54382. this.video.src = url;
  54383. };
  54384. VideoTexture.prototype.dispose = function () {
  54385. _super.prototype.dispose.call(this);
  54386. this.video.removeEventListener("canplay", this._createInternalTexture);
  54387. this.video.removeEventListener("paused", this._updateInternalTexture);
  54388. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54389. this.video.removeEventListener("emptied", this.reset);
  54390. };
  54391. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54392. var video = document.createElement("video");
  54393. var constraintsDeviceId;
  54394. if (constraints && constraints.deviceId) {
  54395. constraintsDeviceId = {
  54396. exact: constraints.deviceId,
  54397. };
  54398. }
  54399. navigator.getUserMedia =
  54400. navigator.getUserMedia ||
  54401. navigator.webkitGetUserMedia ||
  54402. navigator.mozGetUserMedia ||
  54403. navigator.msGetUserMedia;
  54404. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54405. if (navigator.getUserMedia) {
  54406. navigator.getUserMedia({
  54407. video: {
  54408. deviceId: constraintsDeviceId,
  54409. width: {
  54410. min: (constraints && constraints.minWidth) || 256,
  54411. max: (constraints && constraints.maxWidth) || 640,
  54412. },
  54413. height: {
  54414. min: (constraints && constraints.minHeight) || 256,
  54415. max: (constraints && constraints.maxHeight) || 480,
  54416. },
  54417. },
  54418. }, function (stream) {
  54419. if (video.mozSrcObject !== undefined) {
  54420. // hack for Firefox < 19
  54421. video.mozSrcObject = stream;
  54422. }
  54423. else {
  54424. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54425. }
  54426. video.play();
  54427. if (onReady) {
  54428. onReady(new VideoTexture("video", video, scene, true, true));
  54429. }
  54430. }, function (e) {
  54431. BABYLON.Tools.Error(e.name);
  54432. });
  54433. }
  54434. };
  54435. return VideoTexture;
  54436. }(BABYLON.Texture));
  54437. BABYLON.VideoTexture = VideoTexture;
  54438. })(BABYLON || (BABYLON = {}));
  54439. //# sourceMappingURL=babylon.videoTexture.js.map
  54440. var BABYLON;
  54441. (function (BABYLON) {
  54442. var RawTexture = /** @class */ (function (_super) {
  54443. __extends(RawTexture, _super);
  54444. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54446. if (invertY === void 0) { invertY = false; }
  54447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54448. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54449. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54450. _this.format = format;
  54451. _this._engine = scene.getEngine();
  54452. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54453. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54454. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54455. return _this;
  54456. }
  54457. RawTexture.prototype.update = function (data) {
  54458. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54459. };
  54460. // Statics
  54461. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54462. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54463. if (invertY === void 0) { invertY = false; }
  54464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54465. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54466. };
  54467. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54469. if (invertY === void 0) { invertY = false; }
  54470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54471. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54472. };
  54473. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54474. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54475. if (invertY === void 0) { invertY = false; }
  54476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54477. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54478. };
  54479. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54480. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54481. if (invertY === void 0) { invertY = false; }
  54482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54483. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54484. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  54485. };
  54486. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54487. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54488. if (invertY === void 0) { invertY = false; }
  54489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54490. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54491. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  54492. };
  54493. return RawTexture;
  54494. }(BABYLON.Texture));
  54495. BABYLON.RawTexture = RawTexture;
  54496. })(BABYLON || (BABYLON = {}));
  54497. //# sourceMappingURL=babylon.rawTexture.js.map
  54498. var BABYLON;
  54499. (function (BABYLON) {
  54500. var PostProcess = /** @class */ (function () {
  54501. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  54502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  54503. if (defines === void 0) { defines = null; }
  54504. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54505. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  54506. if (blockCompilation === void 0) { blockCompilation = false; }
  54507. this.name = name;
  54508. this.width = -1;
  54509. this.height = -1;
  54510. this.autoClear = true;
  54511. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  54512. this.animations = new Array();
  54513. /*
  54514. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  54515. Can only be used on a single postprocess or on the last one of a chain.
  54516. */
  54517. this.enablePixelPerfectMode = false;
  54518. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  54519. this.alwaysForcePOT = false;
  54520. this.samples = 1;
  54521. this.adaptScaleToCurrentViewport = false;
  54522. this._reusable = false;
  54523. this._textures = new BABYLON.SmartArray(2);
  54524. this._currentRenderTextureInd = 0;
  54525. this._scaleRatio = new BABYLON.Vector2(1, 1);
  54526. this._texelSize = BABYLON.Vector2.Zero();
  54527. // Events
  54528. /**
  54529. * An event triggered when the postprocess is activated.
  54530. * @type {BABYLON.Observable}
  54531. */
  54532. this.onActivateObservable = new BABYLON.Observable();
  54533. /**
  54534. * An event triggered when the postprocess changes its size.
  54535. * @type {BABYLON.Observable}
  54536. */
  54537. this.onSizeChangedObservable = new BABYLON.Observable();
  54538. /**
  54539. * An event triggered when the postprocess applies its effect.
  54540. * @type {BABYLON.Observable}
  54541. */
  54542. this.onApplyObservable = new BABYLON.Observable();
  54543. /**
  54544. * An event triggered before rendering the postprocess
  54545. * @type {BABYLON.Observable}
  54546. */
  54547. this.onBeforeRenderObservable = new BABYLON.Observable();
  54548. /**
  54549. * An event triggered after rendering the postprocess
  54550. * @type {BABYLON.Observable}
  54551. */
  54552. this.onAfterRenderObservable = new BABYLON.Observable();
  54553. if (camera != null) {
  54554. this._camera = camera;
  54555. this._scene = camera.getScene();
  54556. camera.attachPostProcess(this);
  54557. this._engine = this._scene.getEngine();
  54558. this._scene.postProcesses.push(this);
  54559. }
  54560. else if (engine) {
  54561. this._engine = engine;
  54562. this._engine.postProcesses.push(this);
  54563. }
  54564. this._options = options;
  54565. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  54566. this._reusable = reusable || false;
  54567. this._textureType = textureType;
  54568. this._samplers = samplers || [];
  54569. this._samplers.push("textureSampler");
  54570. this._fragmentUrl = fragmentUrl;
  54571. this._vertexUrl = vertexUrl;
  54572. this._parameters = parameters || [];
  54573. this._parameters.push("scale");
  54574. this._indexParameters = indexParameters;
  54575. if (!blockCompilation) {
  54576. this.updateEffect(defines);
  54577. }
  54578. }
  54579. Object.defineProperty(PostProcess.prototype, "onActivate", {
  54580. set: function (callback) {
  54581. if (this._onActivateObserver) {
  54582. this.onActivateObservable.remove(this._onActivateObserver);
  54583. }
  54584. if (callback) {
  54585. this._onActivateObserver = this.onActivateObservable.add(callback);
  54586. }
  54587. },
  54588. enumerable: true,
  54589. configurable: true
  54590. });
  54591. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  54592. set: function (callback) {
  54593. if (this._onSizeChangedObserver) {
  54594. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  54595. }
  54596. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  54597. },
  54598. enumerable: true,
  54599. configurable: true
  54600. });
  54601. Object.defineProperty(PostProcess.prototype, "onApply", {
  54602. set: function (callback) {
  54603. if (this._onApplyObserver) {
  54604. this.onApplyObservable.remove(this._onApplyObserver);
  54605. }
  54606. this._onApplyObserver = this.onApplyObservable.add(callback);
  54607. },
  54608. enumerable: true,
  54609. configurable: true
  54610. });
  54611. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  54612. set: function (callback) {
  54613. if (this._onBeforeRenderObserver) {
  54614. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54615. }
  54616. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54617. },
  54618. enumerable: true,
  54619. configurable: true
  54620. });
  54621. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  54622. set: function (callback) {
  54623. if (this._onAfterRenderObserver) {
  54624. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54625. }
  54626. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54627. },
  54628. enumerable: true,
  54629. configurable: true
  54630. });
  54631. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  54632. get: function () {
  54633. return this._textures.data[this._currentRenderTextureInd];
  54634. },
  54635. set: function (value) {
  54636. this._forcedOutputTexture = value;
  54637. },
  54638. enumerable: true,
  54639. configurable: true
  54640. });
  54641. PostProcess.prototype.getCamera = function () {
  54642. return this._camera;
  54643. };
  54644. Object.defineProperty(PostProcess.prototype, "texelSize", {
  54645. get: function () {
  54646. if (this._shareOutputWithPostProcess) {
  54647. return this._shareOutputWithPostProcess.texelSize;
  54648. }
  54649. if (this._forcedOutputTexture) {
  54650. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  54651. }
  54652. return this._texelSize;
  54653. },
  54654. enumerable: true,
  54655. configurable: true
  54656. });
  54657. PostProcess.prototype.getEngine = function () {
  54658. return this._engine;
  54659. };
  54660. PostProcess.prototype.getEffect = function () {
  54661. return this._effect;
  54662. };
  54663. PostProcess.prototype.shareOutputWith = function (postProcess) {
  54664. this._disposeTextures();
  54665. this._shareOutputWithPostProcess = postProcess;
  54666. return this;
  54667. };
  54668. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  54669. if (defines === void 0) { defines = null; }
  54670. if (uniforms === void 0) { uniforms = null; }
  54671. if (samplers === void 0) { samplers = null; }
  54672. 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);
  54673. };
  54674. PostProcess.prototype.isReusable = function () {
  54675. return this._reusable;
  54676. };
  54677. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  54678. PostProcess.prototype.markTextureDirty = function () {
  54679. this.width = -1;
  54680. };
  54681. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  54682. var _this = this;
  54683. if (sourceTexture === void 0) { sourceTexture = null; }
  54684. camera = camera || this._camera;
  54685. var scene = camera.getScene();
  54686. var engine = scene.getEngine();
  54687. var maxSize = engine.getCaps().maxTextureSize;
  54688. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  54689. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  54690. var desiredWidth = (this._options.width || requiredWidth);
  54691. var desiredHeight = this._options.height || requiredHeight;
  54692. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  54693. if (this.adaptScaleToCurrentViewport) {
  54694. var currentViewport = engine.currentViewport;
  54695. if (currentViewport) {
  54696. desiredWidth *= currentViewport.width;
  54697. desiredHeight *= currentViewport.height;
  54698. }
  54699. }
  54700. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  54701. if (!this._options.width) {
  54702. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  54703. }
  54704. if (!this._options.height) {
  54705. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  54706. }
  54707. }
  54708. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  54709. if (this._textures.length > 0) {
  54710. for (var i = 0; i < this._textures.length; i++) {
  54711. this._engine._releaseTexture(this._textures.data[i]);
  54712. }
  54713. this._textures.reset();
  54714. }
  54715. this.width = desiredWidth;
  54716. this.height = desiredHeight;
  54717. var textureSize = { width: this.width, height: this.height };
  54718. var textureOptions = {
  54719. generateMipMaps: false,
  54720. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  54721. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  54722. samplingMode: this.renderTargetSamplingMode,
  54723. type: this._textureType
  54724. };
  54725. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54726. if (this._reusable) {
  54727. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54728. }
  54729. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  54730. this.onSizeChangedObservable.notifyObservers(this);
  54731. }
  54732. this._textures.forEach(function (texture) {
  54733. if (texture.samples !== _this.samples) {
  54734. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  54735. }
  54736. });
  54737. }
  54738. var target;
  54739. if (this._shareOutputWithPostProcess) {
  54740. target = this._shareOutputWithPostProcess.outputTexture;
  54741. }
  54742. else if (this._forcedOutputTexture) {
  54743. target = this._forcedOutputTexture;
  54744. this.width = this._forcedOutputTexture.width;
  54745. this.height = this._forcedOutputTexture.height;
  54746. }
  54747. else {
  54748. target = this.outputTexture;
  54749. }
  54750. if (this.enablePixelPerfectMode) {
  54751. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  54752. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  54753. }
  54754. else {
  54755. this._scaleRatio.copyFromFloats(1, 1);
  54756. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  54757. }
  54758. this.onActivateObservable.notifyObservers(camera);
  54759. // Clear
  54760. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  54761. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  54762. }
  54763. if (this._reusable) {
  54764. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  54765. }
  54766. };
  54767. Object.defineProperty(PostProcess.prototype, "isSupported", {
  54768. get: function () {
  54769. return this._effect.isSupported;
  54770. },
  54771. enumerable: true,
  54772. configurable: true
  54773. });
  54774. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  54775. get: function () {
  54776. if (this._shareOutputWithPostProcess) {
  54777. return this._shareOutputWithPostProcess.aspectRatio;
  54778. }
  54779. if (this._forcedOutputTexture) {
  54780. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  54781. }
  54782. return this.width / this.height;
  54783. },
  54784. enumerable: true,
  54785. configurable: true
  54786. });
  54787. /**
  54788. * Get a value indicating if the post-process is ready to be used
  54789. * @returns true if the post-process is ready (shader is compiled)
  54790. */
  54791. PostProcess.prototype.isReady = function () {
  54792. return this._effect && this._effect.isReady();
  54793. };
  54794. PostProcess.prototype.apply = function () {
  54795. // Check
  54796. if (!this._effect || !this._effect.isReady())
  54797. return null;
  54798. // States
  54799. this._engine.enableEffect(this._effect);
  54800. this._engine.setState(false);
  54801. this._engine.setDepthBuffer(false);
  54802. this._engine.setDepthWrite(false);
  54803. // Alpha
  54804. this._engine.setAlphaMode(this.alphaMode);
  54805. if (this.alphaConstants) {
  54806. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  54807. }
  54808. // Texture
  54809. var source;
  54810. if (this._shareOutputWithPostProcess) {
  54811. source = this._shareOutputWithPostProcess.outputTexture;
  54812. }
  54813. else if (this._forcedOutputTexture) {
  54814. source = this._forcedOutputTexture;
  54815. }
  54816. else {
  54817. source = this.outputTexture;
  54818. }
  54819. this._effect._bindTexture("textureSampler", source);
  54820. // Parameters
  54821. this._effect.setVector2("scale", this._scaleRatio);
  54822. this.onApplyObservable.notifyObservers(this._effect);
  54823. return this._effect;
  54824. };
  54825. PostProcess.prototype._disposeTextures = function () {
  54826. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  54827. return;
  54828. }
  54829. if (this._textures.length > 0) {
  54830. for (var i = 0; i < this._textures.length; i++) {
  54831. this._engine._releaseTexture(this._textures.data[i]);
  54832. }
  54833. }
  54834. this._textures.dispose();
  54835. };
  54836. PostProcess.prototype.dispose = function (camera) {
  54837. camera = camera || this._camera;
  54838. this._disposeTextures();
  54839. if (this._scene) {
  54840. var index_1 = this._scene.postProcesses.indexOf(this);
  54841. if (index_1 !== -1) {
  54842. this._scene.postProcesses.splice(index_1, 1);
  54843. }
  54844. }
  54845. else {
  54846. var index_2 = this._engine.postProcesses.indexOf(this);
  54847. if (index_2 !== -1) {
  54848. this._engine.postProcesses.splice(index_2, 1);
  54849. }
  54850. }
  54851. if (!camera) {
  54852. return;
  54853. }
  54854. camera.detachPostProcess(this);
  54855. var index = camera._postProcesses.indexOf(this);
  54856. if (index === 0 && camera._postProcesses.length > 0) {
  54857. this._camera._postProcesses[0].markTextureDirty();
  54858. }
  54859. this.onActivateObservable.clear();
  54860. this.onAfterRenderObservable.clear();
  54861. this.onApplyObservable.clear();
  54862. this.onBeforeRenderObservable.clear();
  54863. this.onSizeChangedObservable.clear();
  54864. };
  54865. return PostProcess;
  54866. }());
  54867. BABYLON.PostProcess = PostProcess;
  54868. })(BABYLON || (BABYLON = {}));
  54869. //# sourceMappingURL=babylon.postProcess.js.map
  54870. var BABYLON;
  54871. (function (BABYLON) {
  54872. var PassPostProcess = /** @class */ (function (_super) {
  54873. __extends(PassPostProcess, _super);
  54874. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54875. if (camera === void 0) { camera = null; }
  54876. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54877. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  54878. }
  54879. return PassPostProcess;
  54880. }(BABYLON.PostProcess));
  54881. BABYLON.PassPostProcess = PassPostProcess;
  54882. })(BABYLON || (BABYLON = {}));
  54883. //# sourceMappingURL=babylon.passPostProcess.js.map
  54884. var __assign = (this && this.__assign) || Object.assign || function(t) {
  54885. for (var s, i = 1, n = arguments.length; i < n; i++) {
  54886. s = arguments[i];
  54887. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  54888. t[p] = s[p];
  54889. }
  54890. return t;
  54891. };
  54892. var BABYLON;
  54893. (function (BABYLON) {
  54894. var ShadowGenerator = /** @class */ (function () {
  54895. /**
  54896. * Creates a ShadowGenerator object.
  54897. * A ShadowGenerator is the required tool to use the shadows.
  54898. * Each light casting shadows needs to use its own ShadowGenerator.
  54899. * Required parameters :
  54900. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  54901. * - `light`: the light object generating the shadows.
  54902. * - `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.
  54903. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  54904. */
  54905. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  54906. // Members
  54907. this._bias = 0.00005;
  54908. this._blurBoxOffset = 1;
  54909. this._blurScale = 2;
  54910. this._blurKernel = 1;
  54911. this._useKernelBlur = false;
  54912. this._filter = ShadowGenerator.FILTER_NONE;
  54913. this._darkness = 0;
  54914. this._transparencyShadow = false;
  54915. /**
  54916. * Controls the extent to which the shadows fade out at the edge of the frustum
  54917. * Used only by directionals and spots
  54918. */
  54919. this.frustumEdgeFalloff = 0;
  54920. this.forceBackFacesOnly = false;
  54921. this._lightDirection = BABYLON.Vector3.Zero();
  54922. this._viewMatrix = BABYLON.Matrix.Zero();
  54923. this._projectionMatrix = BABYLON.Matrix.Zero();
  54924. this._transformMatrix = BABYLON.Matrix.Zero();
  54925. this._currentFaceIndex = 0;
  54926. this._currentFaceIndexCache = 0;
  54927. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  54928. this._mapSize = mapSize;
  54929. this._light = light;
  54930. this._scene = light.getScene();
  54931. light._shadowGenerator = this;
  54932. // Texture type fallback from float to int if not supported.
  54933. var caps = this._scene.getEngine().getCaps();
  54934. if (!useFullFloatFirst) {
  54935. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  54936. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54937. }
  54938. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  54939. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54940. }
  54941. else {
  54942. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54943. }
  54944. }
  54945. else {
  54946. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  54947. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54948. }
  54949. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  54950. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54951. }
  54952. else {
  54953. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54954. }
  54955. }
  54956. this._initializeGenerator();
  54957. }
  54958. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  54959. // Static
  54960. get: function () {
  54961. return ShadowGenerator._FILTER_NONE;
  54962. },
  54963. enumerable: true,
  54964. configurable: true
  54965. });
  54966. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  54967. get: function () {
  54968. return ShadowGenerator._FILTER_POISSONSAMPLING;
  54969. },
  54970. enumerable: true,
  54971. configurable: true
  54972. });
  54973. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  54974. get: function () {
  54975. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  54976. },
  54977. enumerable: true,
  54978. configurable: true
  54979. });
  54980. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  54981. get: function () {
  54982. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  54988. get: function () {
  54989. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  54990. },
  54991. enumerable: true,
  54992. configurable: true
  54993. });
  54994. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  54995. get: function () {
  54996. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  54997. },
  54998. enumerable: true,
  54999. configurable: true
  55000. });
  55001. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55002. get: function () {
  55003. return this._bias;
  55004. },
  55005. set: function (bias) {
  55006. this._bias = bias;
  55007. },
  55008. enumerable: true,
  55009. configurable: true
  55010. });
  55011. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55012. get: function () {
  55013. return this._blurBoxOffset;
  55014. },
  55015. set: function (value) {
  55016. if (this._blurBoxOffset === value) {
  55017. return;
  55018. }
  55019. this._blurBoxOffset = value;
  55020. this._disposeBlurPostProcesses();
  55021. },
  55022. enumerable: true,
  55023. configurable: true
  55024. });
  55025. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55026. get: function () {
  55027. return this._blurScale;
  55028. },
  55029. set: function (value) {
  55030. if (this._blurScale === value) {
  55031. return;
  55032. }
  55033. this._blurScale = value;
  55034. this._disposeBlurPostProcesses();
  55035. },
  55036. enumerable: true,
  55037. configurable: true
  55038. });
  55039. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55040. get: function () {
  55041. return this._blurKernel;
  55042. },
  55043. set: function (value) {
  55044. if (this._blurKernel === value) {
  55045. return;
  55046. }
  55047. this._blurKernel = value;
  55048. this._disposeBlurPostProcesses();
  55049. },
  55050. enumerable: true,
  55051. configurable: true
  55052. });
  55053. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55054. get: function () {
  55055. return this._useKernelBlur;
  55056. },
  55057. set: function (value) {
  55058. if (this._useKernelBlur === value) {
  55059. return;
  55060. }
  55061. this._useKernelBlur = value;
  55062. this._disposeBlurPostProcesses();
  55063. },
  55064. enumerable: true,
  55065. configurable: true
  55066. });
  55067. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55068. get: function () {
  55069. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55070. },
  55071. set: function (value) {
  55072. this._depthScale = value;
  55073. },
  55074. enumerable: true,
  55075. configurable: true
  55076. });
  55077. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55078. get: function () {
  55079. return this._filter;
  55080. },
  55081. set: function (value) {
  55082. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55083. if (this._light.needCube()) {
  55084. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55085. this.useExponentialShadowMap = true;
  55086. return;
  55087. }
  55088. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55089. this.useCloseExponentialShadowMap = true;
  55090. return;
  55091. }
  55092. }
  55093. if (this._filter === value) {
  55094. return;
  55095. }
  55096. this._filter = value;
  55097. this._disposeBlurPostProcesses();
  55098. this._applyFilterValues();
  55099. this._light._markMeshesAsLightDirty();
  55100. },
  55101. enumerable: true,
  55102. configurable: true
  55103. });
  55104. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55105. get: function () {
  55106. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55107. },
  55108. set: function (value) {
  55109. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55110. return;
  55111. }
  55112. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55113. },
  55114. enumerable: true,
  55115. configurable: true
  55116. });
  55117. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55118. get: function () {
  55119. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55120. return this.useExponentialShadowMap;
  55121. },
  55122. set: function (value) {
  55123. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55124. this.useExponentialShadowMap = value;
  55125. },
  55126. enumerable: true,
  55127. configurable: true
  55128. });
  55129. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55130. get: function () {
  55131. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55132. return this.useBlurExponentialShadowMap;
  55133. },
  55134. set: function (value) {
  55135. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55136. this.useBlurExponentialShadowMap = value;
  55137. },
  55138. enumerable: true,
  55139. configurable: true
  55140. });
  55141. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55142. get: function () {
  55143. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55144. },
  55145. set: function (value) {
  55146. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55147. return;
  55148. }
  55149. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55150. },
  55151. enumerable: true,
  55152. configurable: true
  55153. });
  55154. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55155. get: function () {
  55156. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55157. },
  55158. set: function (value) {
  55159. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55160. return;
  55161. }
  55162. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55163. },
  55164. enumerable: true,
  55165. configurable: true
  55166. });
  55167. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55168. get: function () {
  55169. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55170. },
  55171. set: function (value) {
  55172. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55173. return;
  55174. }
  55175. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55176. },
  55177. enumerable: true,
  55178. configurable: true
  55179. });
  55180. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55181. get: function () {
  55182. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55183. },
  55184. set: function (value) {
  55185. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55186. return;
  55187. }
  55188. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55189. },
  55190. enumerable: true,
  55191. configurable: true
  55192. });
  55193. /**
  55194. * Returns the darkness value (float).
  55195. */
  55196. ShadowGenerator.prototype.getDarkness = function () {
  55197. return this._darkness;
  55198. };
  55199. /**
  55200. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55201. * Returns the ShadowGenerator.
  55202. */
  55203. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55204. if (darkness >= 1.0)
  55205. this._darkness = 1.0;
  55206. else if (darkness <= 0.0)
  55207. this._darkness = 0.0;
  55208. else
  55209. this._darkness = darkness;
  55210. return this;
  55211. };
  55212. /**
  55213. * Sets the ability to have transparent shadow (boolean).
  55214. * Returns the ShadowGenerator.
  55215. */
  55216. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55217. this._transparencyShadow = hasShadow;
  55218. return this;
  55219. };
  55220. /**
  55221. * Returns a RenderTargetTexture object : the shadow map texture.
  55222. */
  55223. ShadowGenerator.prototype.getShadowMap = function () {
  55224. return this._shadowMap;
  55225. };
  55226. /**
  55227. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55228. */
  55229. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55230. if (this._shadowMap2) {
  55231. return this._shadowMap2;
  55232. }
  55233. return this._shadowMap;
  55234. };
  55235. /**
  55236. * Helper function to add a mesh and its descendants to the list of shadow casters
  55237. * @param mesh Mesh to add
  55238. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55239. */
  55240. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55241. if (includeDescendants === void 0) { includeDescendants = true; }
  55242. if (!this._shadowMap) {
  55243. return this;
  55244. }
  55245. if (!this._shadowMap.renderList) {
  55246. this._shadowMap.renderList = [];
  55247. }
  55248. this._shadowMap.renderList.push(mesh);
  55249. if (includeDescendants) {
  55250. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55251. }
  55252. return this;
  55253. var _a;
  55254. };
  55255. /**
  55256. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55257. * @param mesh Mesh to remove
  55258. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55259. */
  55260. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55261. if (includeDescendants === void 0) { includeDescendants = true; }
  55262. if (!this._shadowMap || !this._shadowMap.renderList) {
  55263. return this;
  55264. }
  55265. var index = this._shadowMap.renderList.indexOf(mesh);
  55266. if (index !== -1) {
  55267. this._shadowMap.renderList.splice(index, 1);
  55268. }
  55269. if (includeDescendants) {
  55270. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55271. var child = _a[_i];
  55272. this.removeShadowCaster(child);
  55273. }
  55274. }
  55275. return this;
  55276. };
  55277. /**
  55278. * Returns the associated light object.
  55279. */
  55280. ShadowGenerator.prototype.getLight = function () {
  55281. return this._light;
  55282. };
  55283. ShadowGenerator.prototype._initializeGenerator = function () {
  55284. this._light._markMeshesAsLightDirty();
  55285. this._initializeShadowMap();
  55286. };
  55287. ShadowGenerator.prototype._initializeShadowMap = function () {
  55288. var _this = this;
  55289. // Render target
  55290. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55291. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55292. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55293. this._shadowMap.anisotropicFilteringLevel = 1;
  55294. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55295. this._shadowMap.renderParticles = false;
  55296. this._shadowMap.ignoreCameraViewport = true;
  55297. // Record Face Index before render.
  55298. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55299. _this._currentFaceIndex = faceIndex;
  55300. });
  55301. // Custom render function.
  55302. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55303. // Blur if required afer render.
  55304. this._shadowMap.onAfterUnbindObservable.add(function () {
  55305. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55306. return;
  55307. }
  55308. var shadowMap = _this.getShadowMapForRendering();
  55309. if (shadowMap) {
  55310. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55311. }
  55312. });
  55313. // Clear according to the chosen filter.
  55314. this._shadowMap.onClearObservable.add(function (engine) {
  55315. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55316. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55317. }
  55318. else {
  55319. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55320. }
  55321. });
  55322. };
  55323. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55324. var _this = this;
  55325. var engine = this._scene.getEngine();
  55326. var targetSize = this._mapSize / this.blurScale;
  55327. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55328. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55329. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55330. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55331. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55332. }
  55333. if (this.useKernelBlur) {
  55334. 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);
  55335. this._kernelBlurXPostprocess.width = targetSize;
  55336. this._kernelBlurXPostprocess.height = targetSize;
  55337. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55338. effect.setTexture("textureSampler", _this._shadowMap);
  55339. });
  55340. 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);
  55341. this._kernelBlurXPostprocess.autoClear = false;
  55342. this._kernelBlurYPostprocess.autoClear = false;
  55343. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55344. this._kernelBlurXPostprocess.packedFloat = true;
  55345. this._kernelBlurYPostprocess.packedFloat = true;
  55346. }
  55347. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55348. }
  55349. else {
  55350. 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);
  55351. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55352. effect.setFloat2("screenSize", targetSize, targetSize);
  55353. effect.setTexture("textureSampler", _this._shadowMap);
  55354. });
  55355. this._boxBlurPostprocess.autoClear = false;
  55356. this._blurPostProcesses = [this._boxBlurPostprocess];
  55357. }
  55358. };
  55359. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55360. var index;
  55361. var engine = this._scene.getEngine();
  55362. if (depthOnlySubMeshes.length) {
  55363. engine.setColorWrite(false);
  55364. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55365. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55366. }
  55367. engine.setColorWrite(true);
  55368. }
  55369. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55370. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55371. }
  55372. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55373. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55374. }
  55375. if (this._transparencyShadow) {
  55376. for (index = 0; index < transparentSubMeshes.length; index++) {
  55377. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55378. }
  55379. }
  55380. };
  55381. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55382. var _this = this;
  55383. var mesh = subMesh.getRenderingMesh();
  55384. var scene = this._scene;
  55385. var engine = scene.getEngine();
  55386. var material = subMesh.getMaterial();
  55387. if (!material) {
  55388. return;
  55389. }
  55390. // Culling
  55391. engine.setState(material.backFaceCulling);
  55392. // Managing instances
  55393. var batch = mesh._getInstancesRenderList(subMesh._id);
  55394. if (batch.mustReturn) {
  55395. return;
  55396. }
  55397. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55398. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55399. engine.enableEffect(this._effect);
  55400. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55401. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55402. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55403. this._effect.setVector3("lightPosition", this.getLight().position);
  55404. if (scene.activeCamera) {
  55405. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55406. }
  55407. // Alpha test
  55408. if (material && material.needAlphaTesting()) {
  55409. var alphaTexture = material.getAlphaTestTexture();
  55410. if (alphaTexture) {
  55411. this._effect.setTexture("diffuseSampler", alphaTexture);
  55412. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55413. }
  55414. }
  55415. // Bones
  55416. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55417. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55418. }
  55419. if (this.forceBackFacesOnly) {
  55420. engine.setState(true, 0, false, true);
  55421. }
  55422. // Draw
  55423. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55424. if (this.forceBackFacesOnly) {
  55425. engine.setState(true, 0, false, false);
  55426. }
  55427. }
  55428. else {
  55429. // Need to reset refresh rate of the shadowMap
  55430. if (this._shadowMap) {
  55431. this._shadowMap.resetRefreshCounter();
  55432. }
  55433. }
  55434. };
  55435. ShadowGenerator.prototype._applyFilterValues = function () {
  55436. if (!this._shadowMap) {
  55437. return;
  55438. }
  55439. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55440. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55441. }
  55442. else {
  55443. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55444. }
  55445. };
  55446. /**
  55447. * Force shader compilation including textures ready check
  55448. */
  55449. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55450. var _this = this;
  55451. var localOptions = __assign({ useInstances: false }, options);
  55452. var shadowMap = this.getShadowMap();
  55453. if (!shadowMap) {
  55454. if (onCompiled) {
  55455. onCompiled(this);
  55456. }
  55457. return;
  55458. }
  55459. var renderList = shadowMap.renderList;
  55460. if (!renderList) {
  55461. if (onCompiled) {
  55462. onCompiled(this);
  55463. }
  55464. return;
  55465. }
  55466. var subMeshes = new Array();
  55467. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  55468. var mesh = renderList_1[_i];
  55469. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  55470. }
  55471. if (subMeshes.length === 0) {
  55472. if (onCompiled) {
  55473. onCompiled(this);
  55474. }
  55475. return;
  55476. }
  55477. var currentIndex = 0;
  55478. var checkReady = function () {
  55479. if (!_this._scene || !_this._scene.getEngine()) {
  55480. return;
  55481. }
  55482. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  55483. currentIndex++;
  55484. if (currentIndex >= subMeshes.length) {
  55485. if (onCompiled) {
  55486. onCompiled(_this);
  55487. }
  55488. return;
  55489. }
  55490. }
  55491. setTimeout(checkReady, 16);
  55492. };
  55493. checkReady();
  55494. };
  55495. /**
  55496. * Boolean : true when the ShadowGenerator is finally computed.
  55497. */
  55498. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  55499. var defines = [];
  55500. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55501. defines.push("#define FLOAT");
  55502. }
  55503. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55504. defines.push("#define ESM");
  55505. }
  55506. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55507. var mesh = subMesh.getMesh();
  55508. var material = subMesh.getMaterial();
  55509. // Alpha test
  55510. if (material && material.needAlphaTesting()) {
  55511. var alphaTexture = material.getAlphaTestTexture();
  55512. if (alphaTexture) {
  55513. defines.push("#define ALPHATEST");
  55514. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55515. attribs.push(BABYLON.VertexBuffer.UVKind);
  55516. defines.push("#define UV1");
  55517. }
  55518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55519. if (alphaTexture.coordinatesIndex === 1) {
  55520. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55521. defines.push("#define UV2");
  55522. }
  55523. }
  55524. }
  55525. }
  55526. // Bones
  55527. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55530. if (mesh.numBoneInfluencers > 4) {
  55531. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55532. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55533. }
  55534. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55535. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55536. }
  55537. else {
  55538. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55539. }
  55540. // Instances
  55541. if (useInstances) {
  55542. defines.push("#define INSTANCES");
  55543. attribs.push("world0");
  55544. attribs.push("world1");
  55545. attribs.push("world2");
  55546. attribs.push("world3");
  55547. }
  55548. // Get correct effect
  55549. var join = defines.join("\n");
  55550. if (this._cachedDefines !== join) {
  55551. this._cachedDefines = join;
  55552. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  55553. }
  55554. if (!this._effect.isReady()) {
  55555. return false;
  55556. }
  55557. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55558. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  55559. this._initializeBlurRTTAndPostProcesses();
  55560. }
  55561. }
  55562. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  55563. return false;
  55564. }
  55565. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  55566. return false;
  55567. }
  55568. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  55569. return false;
  55570. }
  55571. return true;
  55572. };
  55573. /**
  55574. * This creates the defines related to the standard BJS materials.
  55575. */
  55576. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  55577. var scene = this._scene;
  55578. var light = this._light;
  55579. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55580. return;
  55581. }
  55582. defines["SHADOW" + lightIndex] = true;
  55583. if (this.usePoissonSampling) {
  55584. defines["SHADOWPCF" + lightIndex] = true;
  55585. }
  55586. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55587. defines["SHADOWESM" + lightIndex] = true;
  55588. }
  55589. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55590. defines["SHADOWCLOSEESM" + lightIndex] = true;
  55591. }
  55592. if (light.needCube()) {
  55593. defines["SHADOWCUBE" + lightIndex] = true;
  55594. }
  55595. };
  55596. /**
  55597. * This binds shadow lights related to the standard BJS materials.
  55598. * It implies the unifroms available on the materials are the standard BJS ones.
  55599. */
  55600. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  55601. var light = this._light;
  55602. var scene = this._scene;
  55603. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55604. return;
  55605. }
  55606. var camera = scene.activeCamera;
  55607. if (!camera) {
  55608. return;
  55609. }
  55610. var shadowMap = this.getShadowMap();
  55611. if (!shadowMap) {
  55612. return;
  55613. }
  55614. if (!light.needCube()) {
  55615. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  55616. }
  55617. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  55618. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  55619. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  55620. };
  55621. // Methods
  55622. /**
  55623. * Returns a Matrix object : the updated transformation matrix.
  55624. */
  55625. ShadowGenerator.prototype.getTransformMatrix = function () {
  55626. var scene = this._scene;
  55627. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  55628. return this._transformMatrix;
  55629. }
  55630. this._currentRenderID = scene.getRenderId();
  55631. this._currentFaceIndexCache = this._currentFaceIndex;
  55632. var lightPosition = this._light.position;
  55633. if (this._light.computeTransformedInformation()) {
  55634. lightPosition = this._light.transformedPosition;
  55635. }
  55636. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  55637. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  55638. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  55639. }
  55640. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  55641. this._cachedPosition = lightPosition.clone();
  55642. this._cachedDirection = this._lightDirection.clone();
  55643. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  55644. var shadowMap = this.getShadowMap();
  55645. if (shadowMap) {
  55646. var renderList = shadowMap.renderList;
  55647. if (renderList) {
  55648. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  55649. }
  55650. }
  55651. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  55652. }
  55653. return this._transformMatrix;
  55654. };
  55655. ShadowGenerator.prototype.recreateShadowMap = function () {
  55656. var shadowMap = this._shadowMap;
  55657. if (!shadowMap) {
  55658. return;
  55659. }
  55660. // Track render list.
  55661. var renderList = shadowMap.renderList;
  55662. // Clean up existing data.
  55663. this._disposeRTTandPostProcesses();
  55664. // Reinitializes.
  55665. this._initializeGenerator();
  55666. // Reaffect the filter to ensure a correct fallback if necessary.
  55667. this.filter = this.filter;
  55668. // Reaffect the filter.
  55669. this._applyFilterValues();
  55670. // Reaffect Render List.
  55671. this._shadowMap.renderList = renderList;
  55672. };
  55673. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  55674. if (this._shadowMap2) {
  55675. this._shadowMap2.dispose();
  55676. this._shadowMap2 = null;
  55677. }
  55678. if (this._boxBlurPostprocess) {
  55679. this._boxBlurPostprocess.dispose();
  55680. this._boxBlurPostprocess = null;
  55681. }
  55682. if (this._kernelBlurXPostprocess) {
  55683. this._kernelBlurXPostprocess.dispose();
  55684. this._kernelBlurXPostprocess = null;
  55685. }
  55686. if (this._kernelBlurYPostprocess) {
  55687. this._kernelBlurYPostprocess.dispose();
  55688. this._kernelBlurYPostprocess = null;
  55689. }
  55690. this._blurPostProcesses = [];
  55691. };
  55692. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  55693. if (this._shadowMap) {
  55694. this._shadowMap.dispose();
  55695. this._shadowMap = null;
  55696. }
  55697. this._disposeBlurPostProcesses();
  55698. };
  55699. /**
  55700. * Disposes the ShadowGenerator.
  55701. * Returns nothing.
  55702. */
  55703. ShadowGenerator.prototype.dispose = function () {
  55704. this._disposeRTTandPostProcesses();
  55705. if (this._light) {
  55706. this._light._shadowGenerator = null;
  55707. this._light._markMeshesAsLightDirty();
  55708. }
  55709. };
  55710. /**
  55711. * Serializes the ShadowGenerator and returns a serializationObject.
  55712. */
  55713. ShadowGenerator.prototype.serialize = function () {
  55714. var serializationObject = {};
  55715. var shadowMap = this.getShadowMap();
  55716. if (!shadowMap) {
  55717. return serializationObject;
  55718. }
  55719. serializationObject.lightId = this._light.id;
  55720. serializationObject.mapSize = shadowMap.getRenderSize();
  55721. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  55722. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  55723. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55724. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55725. serializationObject.usePoissonSampling = this.usePoissonSampling;
  55726. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  55727. serializationObject.depthScale = this.depthScale;
  55728. serializationObject.darkness = this.getDarkness();
  55729. serializationObject.blurBoxOffset = this.blurBoxOffset;
  55730. serializationObject.blurKernel = this.blurKernel;
  55731. serializationObject.blurScale = this.blurScale;
  55732. serializationObject.useKernelBlur = this.useKernelBlur;
  55733. serializationObject.transparencyShadow = this._transparencyShadow;
  55734. serializationObject.renderList = [];
  55735. if (shadowMap.renderList) {
  55736. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  55737. var mesh = shadowMap.renderList[meshIndex];
  55738. serializationObject.renderList.push(mesh.id);
  55739. }
  55740. }
  55741. return serializationObject;
  55742. };
  55743. /**
  55744. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  55745. */
  55746. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  55747. //casting to point light, as light is missing the position attr and typescript complains.
  55748. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  55749. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  55750. var shadowMap = shadowGenerator.getShadowMap();
  55751. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  55752. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  55753. meshes.forEach(function (mesh) {
  55754. if (!shadowMap) {
  55755. return;
  55756. }
  55757. if (!shadowMap.renderList) {
  55758. shadowMap.renderList = [];
  55759. }
  55760. shadowMap.renderList.push(mesh);
  55761. });
  55762. }
  55763. if (parsedShadowGenerator.usePoissonSampling) {
  55764. shadowGenerator.usePoissonSampling = true;
  55765. }
  55766. else if (parsedShadowGenerator.useExponentialShadowMap) {
  55767. shadowGenerator.useExponentialShadowMap = true;
  55768. }
  55769. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  55770. shadowGenerator.useBlurExponentialShadowMap = true;
  55771. }
  55772. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  55773. shadowGenerator.useCloseExponentialShadowMap = true;
  55774. }
  55775. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  55776. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  55777. }
  55778. else if (parsedShadowGenerator.useVarianceShadowMap) {
  55779. shadowGenerator.useExponentialShadowMap = true;
  55780. }
  55781. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  55782. shadowGenerator.useBlurExponentialShadowMap = true;
  55783. }
  55784. if (parsedShadowGenerator.depthScale) {
  55785. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  55786. }
  55787. if (parsedShadowGenerator.blurScale) {
  55788. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  55789. }
  55790. if (parsedShadowGenerator.blurBoxOffset) {
  55791. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  55792. }
  55793. if (parsedShadowGenerator.useKernelBlur) {
  55794. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  55795. }
  55796. if (parsedShadowGenerator.blurKernel) {
  55797. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  55798. }
  55799. if (parsedShadowGenerator.bias !== undefined) {
  55800. shadowGenerator.bias = parsedShadowGenerator.bias;
  55801. }
  55802. if (parsedShadowGenerator.darkness) {
  55803. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  55804. }
  55805. if (parsedShadowGenerator.transparencyShadow) {
  55806. shadowGenerator.setTransparencyShadow(true);
  55807. }
  55808. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  55809. return shadowGenerator;
  55810. };
  55811. ShadowGenerator._FILTER_NONE = 0;
  55812. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  55813. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  55814. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  55815. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  55816. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  55817. return ShadowGenerator;
  55818. }());
  55819. BABYLON.ShadowGenerator = ShadowGenerator;
  55820. })(BABYLON || (BABYLON = {}));
  55821. //# sourceMappingURL=babylon.shadowGenerator.js.map
  55822. var BABYLON;
  55823. (function (BABYLON) {
  55824. var DefaultLoadingScreen = /** @class */ (function () {
  55825. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  55826. if (_loadingText === void 0) { _loadingText = ""; }
  55827. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  55828. var _this = this;
  55829. this._renderingCanvas = _renderingCanvas;
  55830. this._loadingText = _loadingText;
  55831. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  55832. // Resize
  55833. this._resizeLoadingUI = function () {
  55834. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  55835. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  55836. if (!_this._loadingDiv) {
  55837. return;
  55838. }
  55839. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  55840. _this._loadingDiv.style.left = canvasRect.left + "px";
  55841. _this._loadingDiv.style.top = canvasRect.top + "px";
  55842. _this._loadingDiv.style.width = canvasRect.width + "px";
  55843. _this._loadingDiv.style.height = canvasRect.height + "px";
  55844. };
  55845. }
  55846. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  55847. if (this._loadingDiv) {
  55848. // Do not add a loading screen if there is already one
  55849. return;
  55850. }
  55851. this._loadingDiv = document.createElement("div");
  55852. this._loadingDiv.id = "babylonjsLoadingDiv";
  55853. this._loadingDiv.style.opacity = "0";
  55854. this._loadingDiv.style.transition = "opacity 1.5s ease";
  55855. this._loadingDiv.style.pointerEvents = "none";
  55856. // Loading text
  55857. this._loadingTextDiv = document.createElement("div");
  55858. this._loadingTextDiv.style.position = "absolute";
  55859. this._loadingTextDiv.style.left = "0";
  55860. this._loadingTextDiv.style.top = "50%";
  55861. this._loadingTextDiv.style.marginTop = "80px";
  55862. this._loadingTextDiv.style.width = "100%";
  55863. this._loadingTextDiv.style.height = "20px";
  55864. this._loadingTextDiv.style.fontFamily = "Arial";
  55865. this._loadingTextDiv.style.fontSize = "14px";
  55866. this._loadingTextDiv.style.color = "white";
  55867. this._loadingTextDiv.style.textAlign = "center";
  55868. this._loadingTextDiv.innerHTML = "Loading";
  55869. this._loadingDiv.appendChild(this._loadingTextDiv);
  55870. //set the predefined text
  55871. this._loadingTextDiv.innerHTML = this._loadingText;
  55872. // Generating keyframes
  55873. var style = document.createElement('style');
  55874. style.type = 'text/css';
  55875. 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 }";
  55876. style.innerHTML = keyFrames;
  55877. document.getElementsByTagName('head')[0].appendChild(style);
  55878. // Loading img
  55879. var imgBack = new Image();
  55880. 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";
  55881. imgBack.style.position = "absolute";
  55882. imgBack.style.left = "50%";
  55883. imgBack.style.top = "50%";
  55884. imgBack.style.marginLeft = "-60px";
  55885. imgBack.style.marginTop = "-60px";
  55886. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  55887. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  55888. imgBack.style.transformOrigin = "50% 50%";
  55889. imgBack.style.webkitTransformOrigin = "50% 50%";
  55890. this._loadingDiv.appendChild(imgBack);
  55891. this._resizeLoadingUI();
  55892. window.addEventListener("resize", this._resizeLoadingUI);
  55893. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  55894. document.body.appendChild(this._loadingDiv);
  55895. this._loadingDiv.style.opacity = "1";
  55896. };
  55897. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  55898. var _this = this;
  55899. if (!this._loadingDiv) {
  55900. return;
  55901. }
  55902. var onTransitionEnd = function () {
  55903. if (!_this._loadingDiv) {
  55904. return;
  55905. }
  55906. document.body.removeChild(_this._loadingDiv);
  55907. window.removeEventListener("resize", _this._resizeLoadingUI);
  55908. _this._loadingDiv = null;
  55909. };
  55910. this._loadingDiv.style.opacity = "0";
  55911. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  55912. };
  55913. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  55914. set: function (text) {
  55915. this._loadingText = text;
  55916. if (this._loadingTextDiv) {
  55917. this._loadingTextDiv.innerHTML = this._loadingText;
  55918. }
  55919. },
  55920. enumerable: true,
  55921. configurable: true
  55922. });
  55923. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  55924. get: function () {
  55925. return this._loadingDivBackgroundColor;
  55926. },
  55927. set: function (color) {
  55928. this._loadingDivBackgroundColor = color;
  55929. if (!this._loadingDiv) {
  55930. return;
  55931. }
  55932. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  55933. },
  55934. enumerable: true,
  55935. configurable: true
  55936. });
  55937. return DefaultLoadingScreen;
  55938. }());
  55939. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  55940. })(BABYLON || (BABYLON = {}));
  55941. //# sourceMappingURL=babylon.loadingScreen.js.map
  55942. var BABYLON;
  55943. (function (BABYLON) {
  55944. var SceneLoaderProgressEvent = /** @class */ (function () {
  55945. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  55946. this.lengthComputable = lengthComputable;
  55947. this.loaded = loaded;
  55948. this.total = total;
  55949. }
  55950. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  55951. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  55952. };
  55953. return SceneLoaderProgressEvent;
  55954. }());
  55955. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  55956. var SceneLoader = /** @class */ (function () {
  55957. function SceneLoader() {
  55958. }
  55959. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  55960. get: function () {
  55961. return 0;
  55962. },
  55963. enumerable: true,
  55964. configurable: true
  55965. });
  55966. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  55967. get: function () {
  55968. return 1;
  55969. },
  55970. enumerable: true,
  55971. configurable: true
  55972. });
  55973. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  55974. get: function () {
  55975. return 2;
  55976. },
  55977. enumerable: true,
  55978. configurable: true
  55979. });
  55980. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  55981. get: function () {
  55982. return 3;
  55983. },
  55984. enumerable: true,
  55985. configurable: true
  55986. });
  55987. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  55988. get: function () {
  55989. return SceneLoader._ForceFullSceneLoadingForIncremental;
  55990. },
  55991. set: function (value) {
  55992. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  55993. },
  55994. enumerable: true,
  55995. configurable: true
  55996. });
  55997. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  55998. get: function () {
  55999. return SceneLoader._ShowLoadingScreen;
  56000. },
  56001. set: function (value) {
  56002. SceneLoader._ShowLoadingScreen = value;
  56003. },
  56004. enumerable: true,
  56005. configurable: true
  56006. });
  56007. Object.defineProperty(SceneLoader, "loggingLevel", {
  56008. get: function () {
  56009. return SceneLoader._loggingLevel;
  56010. },
  56011. set: function (value) {
  56012. SceneLoader._loggingLevel = value;
  56013. },
  56014. enumerable: true,
  56015. configurable: true
  56016. });
  56017. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56018. get: function () {
  56019. return SceneLoader._CleanBoneMatrixWeights;
  56020. },
  56021. set: function (value) {
  56022. SceneLoader._CleanBoneMatrixWeights = value;
  56023. },
  56024. enumerable: true,
  56025. configurable: true
  56026. });
  56027. SceneLoader._getDefaultPlugin = function () {
  56028. return SceneLoader._registeredPlugins[".babylon"];
  56029. };
  56030. SceneLoader._getPluginForExtension = function (extension) {
  56031. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56032. if (registeredPlugin) {
  56033. return registeredPlugin;
  56034. }
  56035. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56036. return SceneLoader._getDefaultPlugin();
  56037. };
  56038. SceneLoader._getPluginForDirectLoad = function (data) {
  56039. for (var extension in SceneLoader._registeredPlugins) {
  56040. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56041. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56042. return SceneLoader._registeredPlugins[extension];
  56043. }
  56044. }
  56045. return SceneLoader._getDefaultPlugin();
  56046. };
  56047. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56048. if (sceneFilename.name) {
  56049. sceneFilename = sceneFilename.name;
  56050. }
  56051. var queryStringPosition = sceneFilename.indexOf("?");
  56052. if (queryStringPosition !== -1) {
  56053. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56054. }
  56055. var dotPosition = sceneFilename.lastIndexOf(".");
  56056. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56057. return SceneLoader._getPluginForExtension(extension);
  56058. };
  56059. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56060. SceneLoader._getDirectLoad = function (sceneFilename) {
  56061. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56062. return sceneFilename.substr(5);
  56063. }
  56064. return null;
  56065. };
  56066. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56067. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56068. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56069. var plugin;
  56070. if (registeredPlugin.plugin.createPlugin) {
  56071. plugin = registeredPlugin.plugin.createPlugin();
  56072. }
  56073. else {
  56074. plugin = registeredPlugin.plugin;
  56075. }
  56076. var useArrayBuffer = registeredPlugin.isBinary;
  56077. var database;
  56078. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56079. var dataCallback = function (data, responseURL) {
  56080. if (scene.isDisposed) {
  56081. onError("Scene has been disposed");
  56082. return;
  56083. }
  56084. scene.database = database;
  56085. onSuccess(plugin, data, responseURL);
  56086. };
  56087. var request = null;
  56088. var pluginDisposed = false;
  56089. var onDisposeObservable = plugin.onDisposeObservable;
  56090. if (onDisposeObservable) {
  56091. onDisposeObservable.add(function () {
  56092. pluginDisposed = true;
  56093. if (request) {
  56094. request.abort();
  56095. request = null;
  56096. }
  56097. onDispose();
  56098. });
  56099. }
  56100. var manifestChecked = function () {
  56101. if (pluginDisposed) {
  56102. return;
  56103. }
  56104. var url = rootUrl + sceneFilename;
  56105. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56106. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56107. } : undefined, database, useArrayBuffer, function (request, exception) {
  56108. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56109. });
  56110. };
  56111. if (directLoad) {
  56112. dataCallback(directLoad);
  56113. return plugin;
  56114. }
  56115. if (rootUrl.indexOf("file:") === -1) {
  56116. if (scene.getEngine().enableOfflineSupport) {
  56117. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56118. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56119. }
  56120. else {
  56121. manifestChecked();
  56122. }
  56123. }
  56124. else {
  56125. var fileOrString = sceneFilename;
  56126. if (fileOrString.name) {
  56127. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56128. }
  56129. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56130. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56131. }
  56132. else {
  56133. onError("Unable to find file named " + sceneFilename);
  56134. }
  56135. }
  56136. return plugin;
  56137. };
  56138. // Public functions
  56139. SceneLoader.GetPluginForExtension = function (extension) {
  56140. return SceneLoader._getPluginForExtension(extension).plugin;
  56141. };
  56142. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56143. return !!SceneLoader._registeredPlugins[extension];
  56144. };
  56145. SceneLoader.RegisterPlugin = function (plugin) {
  56146. if (typeof plugin.extensions === "string") {
  56147. var extension = plugin.extensions;
  56148. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56149. plugin: plugin,
  56150. isBinary: false
  56151. };
  56152. }
  56153. else {
  56154. var extensions = plugin.extensions;
  56155. Object.keys(extensions).forEach(function (extension) {
  56156. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56157. plugin: plugin,
  56158. isBinary: extensions[extension].isBinary
  56159. };
  56160. });
  56161. }
  56162. };
  56163. /**
  56164. * Import meshes into a scene
  56165. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56166. * @param rootUrl a string that defines the root url for scene and resources
  56167. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56168. * @param scene the instance of BABYLON.Scene to append to
  56169. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56170. * @param onProgress a callback with a progress event for each file being loaded
  56171. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56172. */
  56173. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56174. if (onSuccess === void 0) { onSuccess = null; }
  56175. if (onProgress === void 0) { onProgress = null; }
  56176. if (onError === void 0) { onError = null; }
  56177. if (pluginExtension === void 0) { pluginExtension = null; }
  56178. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56179. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56180. return null;
  56181. }
  56182. var loadingToken = {};
  56183. scene._addPendingData(loadingToken);
  56184. var disposeHandler = function () {
  56185. scene._removePendingData(loadingToken);
  56186. };
  56187. var errorHandler = function (message, exception) {
  56188. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56189. if (onError) {
  56190. onError(scene, errorMessage, exception);
  56191. }
  56192. else {
  56193. BABYLON.Tools.Error(errorMessage);
  56194. // should the exception be thrown?
  56195. }
  56196. disposeHandler();
  56197. };
  56198. var progressHandler = onProgress ? function (event) {
  56199. try {
  56200. onProgress(event);
  56201. }
  56202. catch (e) {
  56203. errorHandler("Error in onProgress callback", e);
  56204. }
  56205. } : undefined;
  56206. var successHandler = function (meshes, particleSystems, skeletons) {
  56207. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56208. if (onSuccess) {
  56209. try {
  56210. onSuccess(meshes, particleSystems, skeletons);
  56211. }
  56212. catch (e) {
  56213. errorHandler("Error in onSuccess callback", e);
  56214. }
  56215. }
  56216. scene._removePendingData(loadingToken);
  56217. };
  56218. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56219. if (plugin.rewriteRootURL) {
  56220. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56221. }
  56222. if (plugin.importMesh) {
  56223. var syncedPlugin = plugin;
  56224. var meshes = new Array();
  56225. var particleSystems = new Array();
  56226. var skeletons = new Array();
  56227. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56228. return;
  56229. }
  56230. scene.loadingPluginName = plugin.name;
  56231. successHandler(meshes, particleSystems, skeletons);
  56232. }
  56233. else {
  56234. var asyncedPlugin = plugin;
  56235. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56236. scene.loadingPluginName = plugin.name;
  56237. successHandler(meshes, particleSystems, skeletons);
  56238. }, progressHandler, errorHandler);
  56239. }
  56240. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56241. };
  56242. /**
  56243. * Load a scene
  56244. * @param rootUrl a string that defines the root url for scene and resources
  56245. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56246. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56247. * @param onSuccess a callback with the scene when import succeeds
  56248. * @param onProgress a callback with a progress event for each file being loaded
  56249. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56250. */
  56251. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56252. if (onSuccess === void 0) { onSuccess = null; }
  56253. if (onProgress === void 0) { onProgress = null; }
  56254. if (onError === void 0) { onError = null; }
  56255. if (pluginExtension === void 0) { pluginExtension = null; }
  56256. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56257. };
  56258. /**
  56259. * Append a scene
  56260. * @param rootUrl a string that defines the root url for scene and resources
  56261. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56262. * @param scene is the instance of BABYLON.Scene to append to
  56263. * @param onSuccess a callback with the scene when import succeeds
  56264. * @param onProgress a callback with a progress event for each file being loaded
  56265. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56266. */
  56267. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56268. if (onSuccess === void 0) { onSuccess = null; }
  56269. if (onProgress === void 0) { onProgress = null; }
  56270. if (onError === void 0) { onError = null; }
  56271. if (pluginExtension === void 0) { pluginExtension = null; }
  56272. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56273. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56274. return null;
  56275. }
  56276. if (SceneLoader.ShowLoadingScreen) {
  56277. scene.getEngine().displayLoadingUI();
  56278. }
  56279. var loadingToken = {};
  56280. scene._addPendingData(loadingToken);
  56281. var disposeHandler = function () {
  56282. scene._removePendingData(loadingToken);
  56283. scene.getEngine().hideLoadingUI();
  56284. };
  56285. var errorHandler = function (message, exception) {
  56286. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56287. if (onError) {
  56288. onError(scene, errorMessage, exception);
  56289. }
  56290. else {
  56291. BABYLON.Tools.Error(errorMessage);
  56292. // should the exception be thrown?
  56293. }
  56294. disposeHandler();
  56295. };
  56296. var progressHandler = onProgress ? function (event) {
  56297. try {
  56298. onProgress(event);
  56299. }
  56300. catch (e) {
  56301. errorHandler("Error in onProgress callback", e);
  56302. }
  56303. } : undefined;
  56304. var successHandler = function () {
  56305. if (onSuccess) {
  56306. try {
  56307. onSuccess(scene);
  56308. }
  56309. catch (e) {
  56310. errorHandler("Error in onSuccess callback", e);
  56311. }
  56312. }
  56313. scene._removePendingData(loadingToken);
  56314. };
  56315. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56316. if (plugin.load) {
  56317. var syncedPlugin = plugin;
  56318. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56319. return;
  56320. }
  56321. scene.loadingPluginName = plugin.name;
  56322. successHandler();
  56323. }
  56324. else {
  56325. var asyncedPlugin = plugin;
  56326. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56327. scene.loadingPluginName = plugin.name;
  56328. successHandler();
  56329. }, progressHandler, errorHandler);
  56330. }
  56331. if (SceneLoader.ShowLoadingScreen) {
  56332. scene.executeWhenReady(function () {
  56333. scene.getEngine().hideLoadingUI();
  56334. });
  56335. }
  56336. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56337. };
  56338. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56339. if (onSuccess === void 0) { onSuccess = null; }
  56340. if (onProgress === void 0) { onProgress = null; }
  56341. if (onError === void 0) { onError = null; }
  56342. if (pluginExtension === void 0) { pluginExtension = null; }
  56343. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56344. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56345. return null;
  56346. }
  56347. var loadingToken = {};
  56348. scene._addPendingData(loadingToken);
  56349. var disposeHandler = function () {
  56350. scene._removePendingData(loadingToken);
  56351. };
  56352. var errorHandler = function (message, exception) {
  56353. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56354. if (onError) {
  56355. onError(scene, errorMessage, exception);
  56356. }
  56357. else {
  56358. BABYLON.Tools.Error(errorMessage);
  56359. // should the exception be thrown?
  56360. }
  56361. disposeHandler();
  56362. };
  56363. var progressHandler = onProgress ? function (event) {
  56364. try {
  56365. onProgress(event);
  56366. }
  56367. catch (e) {
  56368. errorHandler("Error in onProgress callback", e);
  56369. }
  56370. } : undefined;
  56371. var successHandler = function (assets) {
  56372. if (onSuccess) {
  56373. try {
  56374. onSuccess(assets);
  56375. }
  56376. catch (e) {
  56377. errorHandler("Error in onSuccess callback", e);
  56378. }
  56379. }
  56380. scene._removePendingData(loadingToken);
  56381. };
  56382. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56383. if (plugin.loadAssets) {
  56384. var syncedPlugin = plugin;
  56385. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56386. if (!assetContainer) {
  56387. return;
  56388. }
  56389. scene.loadingPluginName = plugin.name;
  56390. successHandler(assetContainer);
  56391. }
  56392. else if (plugin.loadAssetsAsync) {
  56393. var asyncedPlugin = plugin;
  56394. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56395. if (assetContainer) {
  56396. scene.loadingPluginName = plugin.name;
  56397. successHandler(assetContainer);
  56398. }
  56399. }, progressHandler, errorHandler);
  56400. }
  56401. else {
  56402. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56403. }
  56404. if (SceneLoader.ShowLoadingScreen) {
  56405. scene.executeWhenReady(function () {
  56406. scene.getEngine().hideLoadingUI();
  56407. });
  56408. }
  56409. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56410. };
  56411. // Flags
  56412. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56413. SceneLoader._ShowLoadingScreen = true;
  56414. SceneLoader._CleanBoneMatrixWeights = false;
  56415. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56416. // Members
  56417. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56418. SceneLoader._registeredPlugins = {};
  56419. return SceneLoader;
  56420. }());
  56421. BABYLON.SceneLoader = SceneLoader;
  56422. ;
  56423. })(BABYLON || (BABYLON = {}));
  56424. //# sourceMappingURL=babylon.sceneLoader.js.map
  56425. var BABYLON;
  56426. (function (BABYLON) {
  56427. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56428. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56429. var parsedMaterial = parsedData.materials[index];
  56430. if (parsedMaterial.id === id) {
  56431. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56432. }
  56433. }
  56434. return null;
  56435. };
  56436. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56437. for (var i in names) {
  56438. if (mesh.name === names[i]) {
  56439. hierarchyIds.push(mesh.id);
  56440. return true;
  56441. }
  56442. }
  56443. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56444. hierarchyIds.push(mesh.id);
  56445. return true;
  56446. }
  56447. return false;
  56448. };
  56449. var logOperation = function (operation, producer) {
  56450. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56451. };
  56452. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56453. if (addToScene === void 0) { addToScene = false; }
  56454. var container = new BABYLON.AssetContainer(scene);
  56455. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56456. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56457. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56458. // and avoid problems with multiple concurrent .babylon loads.
  56459. var log = "importScene has failed JSON parse";
  56460. try {
  56461. var parsedData = JSON.parse(data);
  56462. log = "";
  56463. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56464. var index;
  56465. var cache;
  56466. // Lights
  56467. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  56468. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  56469. var parsedLight = parsedData.lights[index];
  56470. var light = BABYLON.Light.Parse(parsedLight, scene);
  56471. if (light) {
  56472. container.lights.push(light);
  56473. log += (index === 0 ? "\n\tLights:" : "");
  56474. log += "\n\t\t" + light.toString(fullDetails);
  56475. }
  56476. }
  56477. }
  56478. // Animations
  56479. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  56480. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  56481. var parsedAnimation = parsedData.animations[index];
  56482. var animation = BABYLON.Animation.Parse(parsedAnimation);
  56483. scene.animations.push(animation);
  56484. container.animations.push(animation);
  56485. log += (index === 0 ? "\n\tAnimations:" : "");
  56486. log += "\n\t\t" + animation.toString(fullDetails);
  56487. }
  56488. }
  56489. // Materials
  56490. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  56491. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56492. var parsedMaterial = parsedData.materials[index];
  56493. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56494. container.materials.push(mat);
  56495. log += (index === 0 ? "\n\tMaterials:" : "");
  56496. log += "\n\t\t" + mat.toString(fullDetails);
  56497. }
  56498. }
  56499. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56500. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  56501. var parsedMultiMaterial = parsedData.multiMaterials[index];
  56502. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56503. container.multiMaterials.push(mmat);
  56504. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  56505. log += "\n\t\t" + mmat.toString(fullDetails);
  56506. }
  56507. }
  56508. // Morph targets
  56509. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  56510. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  56511. var managerData = _a[_i];
  56512. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  56513. }
  56514. }
  56515. // Skeletons
  56516. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56517. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  56518. var parsedSkeleton = parsedData.skeletons[index];
  56519. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56520. container.skeletons.push(skeleton);
  56521. log += (index === 0 ? "\n\tSkeletons:" : "");
  56522. log += "\n\t\t" + skeleton.toString(fullDetails);
  56523. }
  56524. }
  56525. // Geometries
  56526. var geometries = parsedData.geometries;
  56527. if (geometries !== undefined && geometries !== null) {
  56528. var addedGeometry = new Array();
  56529. // Boxes
  56530. var boxes = geometries.boxes;
  56531. if (boxes !== undefined && boxes !== null) {
  56532. for (index = 0, cache = boxes.length; index < cache; index++) {
  56533. var parsedBox = boxes[index];
  56534. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  56535. }
  56536. }
  56537. // Spheres
  56538. var spheres = geometries.spheres;
  56539. if (spheres !== undefined && spheres !== null) {
  56540. for (index = 0, cache = spheres.length; index < cache; index++) {
  56541. var parsedSphere = spheres[index];
  56542. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  56543. }
  56544. }
  56545. // Cylinders
  56546. var cylinders = geometries.cylinders;
  56547. if (cylinders !== undefined && cylinders !== null) {
  56548. for (index = 0, cache = cylinders.length; index < cache; index++) {
  56549. var parsedCylinder = cylinders[index];
  56550. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  56551. }
  56552. }
  56553. // Toruses
  56554. var toruses = geometries.toruses;
  56555. if (toruses !== undefined && toruses !== null) {
  56556. for (index = 0, cache = toruses.length; index < cache; index++) {
  56557. var parsedTorus = toruses[index];
  56558. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  56559. }
  56560. }
  56561. // Grounds
  56562. var grounds = geometries.grounds;
  56563. if (grounds !== undefined && grounds !== null) {
  56564. for (index = 0, cache = grounds.length; index < cache; index++) {
  56565. var parsedGround = grounds[index];
  56566. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  56567. }
  56568. }
  56569. // Planes
  56570. var planes = geometries.planes;
  56571. if (planes !== undefined && planes !== null) {
  56572. for (index = 0, cache = planes.length; index < cache; index++) {
  56573. var parsedPlane = planes[index];
  56574. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  56575. }
  56576. }
  56577. // TorusKnots
  56578. var torusKnots = geometries.torusKnots;
  56579. if (torusKnots !== undefined && torusKnots !== null) {
  56580. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  56581. var parsedTorusKnot = torusKnots[index];
  56582. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  56583. }
  56584. }
  56585. // VertexData
  56586. var vertexData = geometries.vertexData;
  56587. if (vertexData !== undefined && vertexData !== null) {
  56588. for (index = 0, cache = vertexData.length; index < cache; index++) {
  56589. var parsedVertexData = vertexData[index];
  56590. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  56591. }
  56592. }
  56593. addedGeometry.forEach(function (g) {
  56594. if (g) {
  56595. container.geometries.push(g);
  56596. }
  56597. });
  56598. }
  56599. // Transform nodes
  56600. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  56601. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  56602. var parsedTransformNode = parsedData.transformNodes[index];
  56603. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  56604. container.transformNodes.push(node);
  56605. }
  56606. }
  56607. // Meshes
  56608. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56609. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56610. var parsedMesh = parsedData.meshes[index];
  56611. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56612. container.meshes.push(mesh);
  56613. log += (index === 0 ? "\n\tMeshes:" : "");
  56614. log += "\n\t\t" + mesh.toString(fullDetails);
  56615. }
  56616. }
  56617. // Cameras
  56618. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  56619. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  56620. var parsedCamera = parsedData.cameras[index];
  56621. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  56622. container.cameras.push(camera);
  56623. log += (index === 0 ? "\n\tCameras:" : "");
  56624. log += "\n\t\t" + camera.toString(fullDetails);
  56625. }
  56626. }
  56627. // Browsing all the graph to connect the dots
  56628. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  56629. var camera = scene.cameras[index];
  56630. if (camera._waitingParentId) {
  56631. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  56632. camera._waitingParentId = null;
  56633. }
  56634. }
  56635. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56636. var light_1 = scene.lights[index];
  56637. if (light_1 && light_1._waitingParentId) {
  56638. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  56639. light_1._waitingParentId = null;
  56640. }
  56641. }
  56642. // Sounds
  56643. // TODO: add sound
  56644. var loadedSounds = [];
  56645. var loadedSound;
  56646. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  56647. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  56648. var parsedSound = parsedData.sounds[index];
  56649. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56650. if (!parsedSound.url)
  56651. parsedSound.url = parsedSound.name;
  56652. if (!loadedSounds[parsedSound.url]) {
  56653. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  56654. loadedSounds[parsedSound.url] = loadedSound;
  56655. container.sounds.push(loadedSound);
  56656. }
  56657. else {
  56658. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  56659. }
  56660. }
  56661. else {
  56662. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  56663. }
  56664. }
  56665. }
  56666. loadedSounds = [];
  56667. // Connect parents & children and parse actions
  56668. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  56669. var transformNode = scene.transformNodes[index];
  56670. if (transformNode._waitingParentId) {
  56671. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  56672. transformNode._waitingParentId = null;
  56673. }
  56674. }
  56675. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56676. var mesh = scene.meshes[index];
  56677. if (mesh._waitingParentId) {
  56678. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  56679. mesh._waitingParentId = null;
  56680. }
  56681. if (mesh._waitingActions) {
  56682. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  56683. mesh._waitingActions = null;
  56684. }
  56685. }
  56686. // freeze world matrix application
  56687. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56688. var currentMesh = scene.meshes[index];
  56689. if (currentMesh._waitingFreezeWorldMatrix) {
  56690. currentMesh.freezeWorldMatrix();
  56691. currentMesh._waitingFreezeWorldMatrix = null;
  56692. }
  56693. else {
  56694. currentMesh.computeWorldMatrix(true);
  56695. }
  56696. }
  56697. // Particles Systems
  56698. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56699. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56700. var parsedParticleSystem = parsedData.particleSystems[index];
  56701. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56702. container.particleSystems.push(ps);
  56703. }
  56704. }
  56705. // Lens flares
  56706. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  56707. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  56708. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  56709. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  56710. container.lensFlareSystems.push(lf);
  56711. }
  56712. }
  56713. // Shadows
  56714. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  56715. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  56716. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  56717. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  56718. container.shadowGenerators.push(sg);
  56719. }
  56720. }
  56721. // Lights exclusions / inclusions
  56722. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56723. var light_2 = scene.lights[index];
  56724. // Excluded check
  56725. if (light_2._excludedMeshesIds.length > 0) {
  56726. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  56727. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  56728. if (excludedMesh) {
  56729. light_2.excludedMeshes.push(excludedMesh);
  56730. }
  56731. }
  56732. light_2._excludedMeshesIds = [];
  56733. }
  56734. // Included check
  56735. if (light_2._includedOnlyMeshesIds.length > 0) {
  56736. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  56737. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  56738. if (includedOnlyMesh) {
  56739. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  56740. }
  56741. }
  56742. light_2._includedOnlyMeshesIds = [];
  56743. }
  56744. }
  56745. // Actions (scene)
  56746. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  56747. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  56748. }
  56749. if (!addToScene) {
  56750. container.removeAllFromScene();
  56751. }
  56752. return container;
  56753. }
  56754. catch (err) {
  56755. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  56756. if (onError) {
  56757. onError(msg, err);
  56758. }
  56759. else {
  56760. BABYLON.Tools.Log(msg);
  56761. throw err;
  56762. }
  56763. }
  56764. finally {
  56765. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56766. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56767. }
  56768. }
  56769. return null;
  56770. };
  56771. BABYLON.SceneLoader.RegisterPlugin({
  56772. name: "babylon.js",
  56773. extensions: ".babylon",
  56774. canDirectLoad: function (data) {
  56775. if (data.indexOf("babylon") !== -1) {
  56776. return true;
  56777. }
  56778. return false;
  56779. },
  56780. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  56781. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56782. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56783. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56784. // and avoid problems with multiple concurrent .babylon loads.
  56785. var log = "importMesh has failed JSON parse";
  56786. try {
  56787. var parsedData = JSON.parse(data);
  56788. log = "";
  56789. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56790. if (!meshesNames) {
  56791. meshesNames = null;
  56792. }
  56793. else if (!Array.isArray(meshesNames)) {
  56794. meshesNames = [meshesNames];
  56795. }
  56796. var hierarchyIds = new Array();
  56797. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56798. var loadedSkeletonsIds = [];
  56799. var loadedMaterialsIds = [];
  56800. var index;
  56801. var cache;
  56802. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56803. var parsedMesh = parsedData.meshes[index];
  56804. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  56805. if (meshesNames !== null) {
  56806. // Remove found mesh name from list.
  56807. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  56808. }
  56809. //Geometry?
  56810. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  56811. //does the file contain geometries?
  56812. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  56813. //find the correct geometry and add it to the scene
  56814. var found = false;
  56815. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  56816. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  56817. return;
  56818. }
  56819. else {
  56820. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  56821. if (parsedGeometryData.id === parsedMesh.geometryId) {
  56822. switch (geometryType) {
  56823. case "boxes":
  56824. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  56825. break;
  56826. case "spheres":
  56827. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  56828. break;
  56829. case "cylinders":
  56830. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  56831. break;
  56832. case "toruses":
  56833. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  56834. break;
  56835. case "grounds":
  56836. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  56837. break;
  56838. case "planes":
  56839. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  56840. break;
  56841. case "torusKnots":
  56842. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  56843. break;
  56844. case "vertexData":
  56845. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  56846. break;
  56847. }
  56848. found = true;
  56849. }
  56850. });
  56851. }
  56852. });
  56853. if (found === false) {
  56854. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  56855. }
  56856. }
  56857. }
  56858. // Material ?
  56859. if (parsedMesh.materialId) {
  56860. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  56861. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56862. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  56863. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  56864. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  56865. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  56866. var subMatId = parsedMultiMaterial.materials[matIndex];
  56867. loadedMaterialsIds.push(subMatId);
  56868. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  56869. log += "\n\tMaterial " + mat.toString(fullDetails);
  56870. }
  56871. loadedMaterialsIds.push(parsedMultiMaterial.id);
  56872. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56873. materialFound = true;
  56874. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  56875. break;
  56876. }
  56877. }
  56878. }
  56879. if (materialFound === false) {
  56880. loadedMaterialsIds.push(parsedMesh.materialId);
  56881. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  56882. if (!mat) {
  56883. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  56884. }
  56885. else {
  56886. log += "\n\tMaterial " + mat.toString(fullDetails);
  56887. }
  56888. }
  56889. }
  56890. // Skeleton ?
  56891. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56892. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  56893. if (skeletonAlreadyLoaded === false) {
  56894. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  56895. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  56896. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  56897. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56898. skeletons.push(skeleton);
  56899. loadedSkeletonsIds.push(parsedSkeleton.id);
  56900. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  56901. }
  56902. }
  56903. }
  56904. }
  56905. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56906. meshes.push(mesh);
  56907. log += "\n\tMesh " + mesh.toString(fullDetails);
  56908. }
  56909. }
  56910. // Connecting parents
  56911. var currentMesh;
  56912. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56913. currentMesh = scene.meshes[index];
  56914. if (currentMesh._waitingParentId) {
  56915. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  56916. currentMesh._waitingParentId = null;
  56917. }
  56918. }
  56919. // freeze and compute world matrix application
  56920. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56921. currentMesh = scene.meshes[index];
  56922. if (currentMesh._waitingFreezeWorldMatrix) {
  56923. currentMesh.freezeWorldMatrix();
  56924. currentMesh._waitingFreezeWorldMatrix = null;
  56925. }
  56926. else {
  56927. currentMesh.computeWorldMatrix(true);
  56928. }
  56929. }
  56930. }
  56931. // Particles
  56932. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56933. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56934. var parsedParticleSystem = parsedData.particleSystems[index];
  56935. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  56936. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  56937. }
  56938. }
  56939. }
  56940. return true;
  56941. }
  56942. catch (err) {
  56943. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  56944. if (onError) {
  56945. onError(msg, err);
  56946. }
  56947. else {
  56948. BABYLON.Tools.Log(msg);
  56949. throw err;
  56950. }
  56951. }
  56952. finally {
  56953. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56954. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56955. }
  56956. }
  56957. return false;
  56958. },
  56959. load: function (scene, data, rootUrl, onError) {
  56960. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56961. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56962. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56963. // and avoid problems with multiple concurrent .babylon loads.
  56964. var log = "importScene has failed JSON parse";
  56965. try {
  56966. var parsedData = JSON.parse(data);
  56967. log = "";
  56968. // Scene
  56969. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  56970. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  56971. }
  56972. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  56973. scene.autoClear = parsedData.autoClear;
  56974. }
  56975. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  56976. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  56977. }
  56978. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  56979. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  56980. }
  56981. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  56982. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  56983. }
  56984. // Fog
  56985. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  56986. scene.fogMode = parsedData.fogMode;
  56987. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  56988. scene.fogStart = parsedData.fogStart;
  56989. scene.fogEnd = parsedData.fogEnd;
  56990. scene.fogDensity = parsedData.fogDensity;
  56991. log += "\tFog mode for scene: ";
  56992. switch (scene.fogMode) {
  56993. // getters not compiling, so using hardcoded
  56994. case 1:
  56995. log += "exp\n";
  56996. break;
  56997. case 2:
  56998. log += "exp2\n";
  56999. break;
  57000. case 3:
  57001. log += "linear\n";
  57002. break;
  57003. }
  57004. }
  57005. //Physics
  57006. if (parsedData.physicsEnabled) {
  57007. var physicsPlugin;
  57008. if (parsedData.physicsEngine === "cannon") {
  57009. physicsPlugin = new BABYLON.CannonJSPlugin();
  57010. }
  57011. else if (parsedData.physicsEngine === "oimo") {
  57012. physicsPlugin = new BABYLON.OimoJSPlugin();
  57013. }
  57014. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57015. //else - default engine, which is currently oimo
  57016. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57017. scene.enablePhysics(physicsGravity, physicsPlugin);
  57018. }
  57019. // Metadata
  57020. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57021. scene.metadata = parsedData.metadata;
  57022. }
  57023. //collisions, if defined. otherwise, default is true
  57024. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57025. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57026. }
  57027. scene.workerCollisions = !!parsedData.workerCollisions;
  57028. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57029. if (!container) {
  57030. return false;
  57031. }
  57032. if (parsedData.autoAnimate) {
  57033. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57034. }
  57035. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57036. scene.setActiveCameraByID(parsedData.activeCameraID);
  57037. }
  57038. // Environment texture
  57039. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57040. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57041. if (parsedData.createDefaultSkybox === true) {
  57042. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57043. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57044. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57045. }
  57046. }
  57047. // Finish
  57048. return true;
  57049. }
  57050. catch (err) {
  57051. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57052. if (onError) {
  57053. onError(msg, err);
  57054. }
  57055. else {
  57056. BABYLON.Tools.Log(msg);
  57057. throw err;
  57058. }
  57059. }
  57060. finally {
  57061. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57062. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57063. }
  57064. }
  57065. return false;
  57066. },
  57067. loadAssets: function (scene, data, rootUrl, onError) {
  57068. var container = loadAssets(scene, data, rootUrl, onerror);
  57069. return container;
  57070. }
  57071. });
  57072. })(BABYLON || (BABYLON = {}));
  57073. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57074. var BABYLON;
  57075. (function (BABYLON) {
  57076. var FilesInput = /** @class */ (function () {
  57077. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57078. this.onProcessFileCallback = function () { return true; };
  57079. this._engine = engine;
  57080. this._currentScene = scene;
  57081. this._sceneLoadedCallback = sceneLoadedCallback;
  57082. this._progressCallback = progressCallback;
  57083. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57084. this._textureLoadingCallback = textureLoadingCallback;
  57085. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57086. this._onReloadCallback = onReloadCallback;
  57087. this._errorCallback = errorCallback;
  57088. }
  57089. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57090. var _this = this;
  57091. if (elementToMonitor) {
  57092. this._elementToMonitor = elementToMonitor;
  57093. this._dragEnterHandler = function (e) { _this.drag(e); };
  57094. this._dragOverHandler = function (e) { _this.drag(e); };
  57095. this._dropHandler = function (e) { _this.drop(e); };
  57096. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57097. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57098. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57099. }
  57100. };
  57101. FilesInput.prototype.dispose = function () {
  57102. if (!this._elementToMonitor) {
  57103. return;
  57104. }
  57105. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57106. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57107. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57108. };
  57109. FilesInput.prototype.renderFunction = function () {
  57110. if (this._additionalRenderLoopLogicCallback) {
  57111. this._additionalRenderLoopLogicCallback();
  57112. }
  57113. if (this._currentScene) {
  57114. if (this._textureLoadingCallback) {
  57115. var remaining = this._currentScene.getWaitingItemsCount();
  57116. if (remaining > 0) {
  57117. this._textureLoadingCallback(remaining);
  57118. }
  57119. }
  57120. this._currentScene.render();
  57121. }
  57122. };
  57123. FilesInput.prototype.drag = function (e) {
  57124. e.stopPropagation();
  57125. e.preventDefault();
  57126. };
  57127. FilesInput.prototype.drop = function (eventDrop) {
  57128. eventDrop.stopPropagation();
  57129. eventDrop.preventDefault();
  57130. this.loadFiles(eventDrop);
  57131. };
  57132. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57133. var _this = this;
  57134. var reader = folder.createReader();
  57135. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57136. reader.readEntries(function (entries) {
  57137. remaining.count += entries.length;
  57138. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57139. var entry = entries_1[_i];
  57140. if (entry.isFile) {
  57141. entry.file(function (file) {
  57142. file.correctName = relativePath + file.name;
  57143. files.push(file);
  57144. if (--remaining.count === 0) {
  57145. callback();
  57146. }
  57147. });
  57148. }
  57149. else if (entry.isDirectory) {
  57150. _this._traverseFolder(entry, files, remaining, callback);
  57151. }
  57152. }
  57153. if (--remaining.count) {
  57154. callback();
  57155. }
  57156. });
  57157. };
  57158. FilesInput.prototype._processFiles = function (files) {
  57159. for (var i = 0; i < files.length; i++) {
  57160. var name = files[i].correctName.toLowerCase();
  57161. var extension = name.split('.').pop();
  57162. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57163. continue;
  57164. }
  57165. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57166. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57167. this._sceneFileToLoad = files[i];
  57168. }
  57169. else {
  57170. FilesInput.FilesToLoad[name] = files[i];
  57171. }
  57172. }
  57173. };
  57174. FilesInput.prototype.loadFiles = function (event) {
  57175. var _this = this;
  57176. if (this._startingProcessingFilesCallback)
  57177. this._startingProcessingFilesCallback();
  57178. // Handling data transfer via drag'n'drop
  57179. if (event && event.dataTransfer && event.dataTransfer.files) {
  57180. this._filesToLoad = event.dataTransfer.files;
  57181. }
  57182. // Handling files from input files
  57183. if (event && event.target && event.target.files) {
  57184. this._filesToLoad = event.target.files;
  57185. }
  57186. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57187. var files_1 = new Array();
  57188. var folders = [];
  57189. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57190. for (var i = 0; i < this._filesToLoad.length; i++) {
  57191. var fileToLoad = this._filesToLoad[i];
  57192. var name_1 = fileToLoad.name.toLowerCase();
  57193. var entry = void 0;
  57194. fileToLoad.correctName = name_1;
  57195. if (items) {
  57196. var item = items[i];
  57197. if (item.getAsEntry) {
  57198. entry = item.getAsEntry();
  57199. }
  57200. else if (item.webkitGetAsEntry) {
  57201. entry = item.webkitGetAsEntry();
  57202. }
  57203. }
  57204. if (!entry) {
  57205. files_1.push(fileToLoad);
  57206. }
  57207. else {
  57208. if (entry.isDirectory) {
  57209. folders.push(entry);
  57210. }
  57211. else {
  57212. files_1.push(fileToLoad);
  57213. }
  57214. }
  57215. }
  57216. if (folders.length === 0) {
  57217. this._processFiles(files_1);
  57218. this._processReload();
  57219. }
  57220. else {
  57221. var remaining = { count: folders.length };
  57222. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57223. var folder = folders_1[_i];
  57224. this._traverseFolder(folder, files_1, remaining, function () {
  57225. _this._processFiles(files_1);
  57226. if (remaining.count === 0) {
  57227. _this._processReload();
  57228. }
  57229. });
  57230. }
  57231. }
  57232. }
  57233. };
  57234. FilesInput.prototype._processReload = function () {
  57235. if (this._onReloadCallback) {
  57236. this._onReloadCallback(this._sceneFileToLoad);
  57237. }
  57238. else {
  57239. this.reload();
  57240. }
  57241. };
  57242. FilesInput.prototype.reload = function () {
  57243. var _this = this;
  57244. // If a scene file has been provided
  57245. if (this._sceneFileToLoad) {
  57246. if (this._currentScene) {
  57247. if (BABYLON.Tools.errorsCount > 0) {
  57248. BABYLON.Tools.ClearLogCache();
  57249. }
  57250. this._engine.stopRenderLoop();
  57251. this._currentScene.dispose();
  57252. }
  57253. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57254. _this._currentScene = newScene;
  57255. if (_this._sceneLoadedCallback) {
  57256. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57257. }
  57258. // Wait for textures and shaders to be ready
  57259. _this._currentScene.executeWhenReady(function () {
  57260. _this._engine.runRenderLoop(function () {
  57261. _this.renderFunction();
  57262. });
  57263. });
  57264. }, function (progress) {
  57265. if (_this._progressCallback) {
  57266. _this._progressCallback(progress);
  57267. }
  57268. }, function (scene, message) {
  57269. _this._currentScene = scene;
  57270. if (_this._errorCallback) {
  57271. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57272. }
  57273. });
  57274. }
  57275. else {
  57276. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57277. }
  57278. };
  57279. FilesInput.FilesToLoad = {};
  57280. return FilesInput;
  57281. }());
  57282. BABYLON.FilesInput = FilesInput;
  57283. })(BABYLON || (BABYLON = {}));
  57284. //# sourceMappingURL=babylon.filesInput.js.map
  57285. var BABYLON;
  57286. (function (BABYLON) {
  57287. /**
  57288. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57289. * The underlying implementation relies on an associative array to ensure the best performances.
  57290. * The value can be anything including 'null' but except 'undefined'
  57291. */
  57292. var StringDictionary = /** @class */ (function () {
  57293. function StringDictionary() {
  57294. this._count = 0;
  57295. this._data = {};
  57296. }
  57297. /**
  57298. * This will clear this dictionary and copy the content from the 'source' one.
  57299. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57300. * @param source the dictionary to take the content from and copy to this dictionary
  57301. */
  57302. StringDictionary.prototype.copyFrom = function (source) {
  57303. var _this = this;
  57304. this.clear();
  57305. source.forEach(function (t, v) { return _this.add(t, v); });
  57306. };
  57307. /**
  57308. * Get a value based from its key
  57309. * @param key the given key to get the matching value from
  57310. * @return the value if found, otherwise undefined is returned
  57311. */
  57312. StringDictionary.prototype.get = function (key) {
  57313. var val = this._data[key];
  57314. if (val !== undefined) {
  57315. return val;
  57316. }
  57317. return undefined;
  57318. };
  57319. /**
  57320. * Get a value from its key or add it if it doesn't exist.
  57321. * This method will ensure you that a given key/data will be present in the dictionary.
  57322. * @param key the given key to get the matching value from
  57323. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57324. * The factory will only be invoked if there's no data for the given key.
  57325. * @return the value corresponding to the key.
  57326. */
  57327. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57328. var val = this.get(key);
  57329. if (val !== undefined) {
  57330. return val;
  57331. }
  57332. val = factory(key);
  57333. if (val) {
  57334. this.add(key, val);
  57335. }
  57336. return val;
  57337. };
  57338. /**
  57339. * Get a value from its key if present in the dictionary otherwise add it
  57340. * @param key the key to get the value from
  57341. * @param val if there's no such key/value pair in the dictionary add it with this value
  57342. * @return the value corresponding to the key
  57343. */
  57344. StringDictionary.prototype.getOrAdd = function (key, val) {
  57345. var curVal = this.get(key);
  57346. if (curVal !== undefined) {
  57347. return curVal;
  57348. }
  57349. this.add(key, val);
  57350. return val;
  57351. };
  57352. /**
  57353. * Check if there's a given key in the dictionary
  57354. * @param key the key to check for
  57355. * @return true if the key is present, false otherwise
  57356. */
  57357. StringDictionary.prototype.contains = function (key) {
  57358. return this._data[key] !== undefined;
  57359. };
  57360. /**
  57361. * Add a new key and its corresponding value
  57362. * @param key the key to add
  57363. * @param value the value corresponding to the key
  57364. * @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
  57365. */
  57366. StringDictionary.prototype.add = function (key, value) {
  57367. if (this._data[key] !== undefined) {
  57368. return false;
  57369. }
  57370. this._data[key] = value;
  57371. ++this._count;
  57372. return true;
  57373. };
  57374. StringDictionary.prototype.set = function (key, value) {
  57375. if (this._data[key] === undefined) {
  57376. return false;
  57377. }
  57378. this._data[key] = value;
  57379. return true;
  57380. };
  57381. /**
  57382. * Get the element of the given key and remove it from the dictionary
  57383. * @param key
  57384. */
  57385. StringDictionary.prototype.getAndRemove = function (key) {
  57386. var val = this.get(key);
  57387. if (val !== undefined) {
  57388. delete this._data[key];
  57389. --this._count;
  57390. return val;
  57391. }
  57392. return null;
  57393. };
  57394. /**
  57395. * Remove a key/value from the dictionary.
  57396. * @param key the key to remove
  57397. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57398. */
  57399. StringDictionary.prototype.remove = function (key) {
  57400. if (this.contains(key)) {
  57401. delete this._data[key];
  57402. --this._count;
  57403. return true;
  57404. }
  57405. return false;
  57406. };
  57407. /**
  57408. * Clear the whole content of the dictionary
  57409. */
  57410. StringDictionary.prototype.clear = function () {
  57411. this._data = {};
  57412. this._count = 0;
  57413. };
  57414. Object.defineProperty(StringDictionary.prototype, "count", {
  57415. get: function () {
  57416. return this._count;
  57417. },
  57418. enumerable: true,
  57419. configurable: true
  57420. });
  57421. /**
  57422. * Execute a callback on each key/val of the dictionary.
  57423. * Note that you can remove any element in this dictionary in the callback implementation
  57424. * @param callback the callback to execute on a given key/value pair
  57425. */
  57426. StringDictionary.prototype.forEach = function (callback) {
  57427. for (var cur in this._data) {
  57428. var val = this._data[cur];
  57429. callback(cur, val);
  57430. }
  57431. };
  57432. /**
  57433. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57434. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57435. * Note that you can remove any element in this dictionary in the callback implementation
  57436. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57437. */
  57438. StringDictionary.prototype.first = function (callback) {
  57439. for (var cur in this._data) {
  57440. var val = this._data[cur];
  57441. var res = callback(cur, val);
  57442. if (res) {
  57443. return res;
  57444. }
  57445. }
  57446. return null;
  57447. };
  57448. return StringDictionary;
  57449. }());
  57450. BABYLON.StringDictionary = StringDictionary;
  57451. })(BABYLON || (BABYLON = {}));
  57452. //# sourceMappingURL=babylon.stringDictionary.js.map
  57453. var BABYLON;
  57454. (function (BABYLON) {
  57455. var Tags = /** @class */ (function () {
  57456. function Tags() {
  57457. }
  57458. Tags.EnableFor = function (obj) {
  57459. obj._tags = obj._tags || {};
  57460. obj.hasTags = function () {
  57461. return Tags.HasTags(obj);
  57462. };
  57463. obj.addTags = function (tagsString) {
  57464. return Tags.AddTagsTo(obj, tagsString);
  57465. };
  57466. obj.removeTags = function (tagsString) {
  57467. return Tags.RemoveTagsFrom(obj, tagsString);
  57468. };
  57469. obj.matchesTagsQuery = function (tagsQuery) {
  57470. return Tags.MatchesQuery(obj, tagsQuery);
  57471. };
  57472. };
  57473. Tags.DisableFor = function (obj) {
  57474. delete obj._tags;
  57475. delete obj.hasTags;
  57476. delete obj.addTags;
  57477. delete obj.removeTags;
  57478. delete obj.matchesTagsQuery;
  57479. };
  57480. Tags.HasTags = function (obj) {
  57481. if (!obj._tags) {
  57482. return false;
  57483. }
  57484. return !BABYLON.Tools.IsEmpty(obj._tags);
  57485. };
  57486. Tags.GetTags = function (obj, asString) {
  57487. if (asString === void 0) { asString = true; }
  57488. if (!obj._tags) {
  57489. return null;
  57490. }
  57491. if (asString) {
  57492. var tagsArray = [];
  57493. for (var tag in obj._tags) {
  57494. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  57495. tagsArray.push(tag);
  57496. }
  57497. }
  57498. return tagsArray.join(" ");
  57499. }
  57500. else {
  57501. return obj._tags;
  57502. }
  57503. };
  57504. // the tags 'true' and 'false' are reserved and cannot be used as tags
  57505. // a tag cannot start with '||', '&&', and '!'
  57506. // it cannot contain whitespaces
  57507. Tags.AddTagsTo = function (obj, tagsString) {
  57508. if (!tagsString) {
  57509. return;
  57510. }
  57511. if (typeof tagsString !== "string") {
  57512. return;
  57513. }
  57514. var tags = tagsString.split(" ");
  57515. tags.forEach(function (tag, index, array) {
  57516. Tags._AddTagTo(obj, tag);
  57517. });
  57518. };
  57519. Tags._AddTagTo = function (obj, tag) {
  57520. tag = tag.trim();
  57521. if (tag === "" || tag === "true" || tag === "false") {
  57522. return;
  57523. }
  57524. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  57525. return;
  57526. }
  57527. Tags.EnableFor(obj);
  57528. obj._tags[tag] = true;
  57529. };
  57530. Tags.RemoveTagsFrom = function (obj, tagsString) {
  57531. if (!Tags.HasTags(obj)) {
  57532. return;
  57533. }
  57534. var tags = tagsString.split(" ");
  57535. for (var t in tags) {
  57536. Tags._RemoveTagFrom(obj, tags[t]);
  57537. }
  57538. };
  57539. Tags._RemoveTagFrom = function (obj, tag) {
  57540. delete obj._tags[tag];
  57541. };
  57542. Tags.MatchesQuery = function (obj, tagsQuery) {
  57543. if (tagsQuery === undefined) {
  57544. return true;
  57545. }
  57546. if (tagsQuery === "") {
  57547. return Tags.HasTags(obj);
  57548. }
  57549. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  57550. };
  57551. return Tags;
  57552. }());
  57553. BABYLON.Tags = Tags;
  57554. })(BABYLON || (BABYLON = {}));
  57555. //# sourceMappingURL=babylon.tags.js.map
  57556. var BABYLON;
  57557. (function (BABYLON) {
  57558. var AndOrNotEvaluator = /** @class */ (function () {
  57559. function AndOrNotEvaluator() {
  57560. }
  57561. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  57562. if (!query.match(/\([^\(\)]*\)/g)) {
  57563. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  57564. }
  57565. else {
  57566. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  57567. // remove parenthesis
  57568. r = r.slice(1, r.length - 1);
  57569. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  57570. });
  57571. }
  57572. if (query === "true") {
  57573. return true;
  57574. }
  57575. if (query === "false") {
  57576. return false;
  57577. }
  57578. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  57579. };
  57580. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  57581. evaluateCallback = evaluateCallback || (function (r) {
  57582. return r === "true" ? true : false;
  57583. });
  57584. var result;
  57585. var or = parenthesisContent.split("||");
  57586. for (var i in or) {
  57587. if (or.hasOwnProperty(i)) {
  57588. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  57589. var and = ori.split("&&");
  57590. if (and.length > 1) {
  57591. for (var j = 0; j < and.length; ++j) {
  57592. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  57593. if (andj !== "true" && andj !== "false") {
  57594. if (andj[0] === "!") {
  57595. result = !evaluateCallback(andj.substring(1));
  57596. }
  57597. else {
  57598. result = evaluateCallback(andj);
  57599. }
  57600. }
  57601. else {
  57602. result = andj === "true" ? true : false;
  57603. }
  57604. if (!result) {
  57605. ori = "false";
  57606. break;
  57607. }
  57608. }
  57609. }
  57610. if (result || ori === "true") {
  57611. result = true;
  57612. break;
  57613. }
  57614. // result equals false (or undefined)
  57615. if (ori !== "true" && ori !== "false") {
  57616. if (ori[0] === "!") {
  57617. result = !evaluateCallback(ori.substring(1));
  57618. }
  57619. else {
  57620. result = evaluateCallback(ori);
  57621. }
  57622. }
  57623. else {
  57624. result = ori === "true" ? true : false;
  57625. }
  57626. }
  57627. }
  57628. // the whole parenthesis scope is replaced by 'true' or 'false'
  57629. return result ? "true" : "false";
  57630. };
  57631. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  57632. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  57633. // remove whitespaces
  57634. r = r.replace(/[\s]/g, function () { return ""; });
  57635. return r.length % 2 ? "!" : "";
  57636. });
  57637. booleanString = booleanString.trim();
  57638. if (booleanString === "!true") {
  57639. booleanString = "false";
  57640. }
  57641. else if (booleanString === "!false") {
  57642. booleanString = "true";
  57643. }
  57644. return booleanString;
  57645. };
  57646. return AndOrNotEvaluator;
  57647. }());
  57648. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  57649. })(BABYLON || (BABYLON = {}));
  57650. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  57651. var BABYLON;
  57652. (function (BABYLON) {
  57653. var Database = /** @class */ (function () {
  57654. function Database(urlToScene, callbackManifestChecked) {
  57655. // Handling various flavors of prefixed version of IndexedDB
  57656. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  57657. this.callbackManifestChecked = callbackManifestChecked;
  57658. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  57659. this.db = null;
  57660. this._enableSceneOffline = false;
  57661. this._enableTexturesOffline = false;
  57662. this.manifestVersionFound = 0;
  57663. this.mustUpdateRessources = false;
  57664. this.hasReachedQuota = false;
  57665. if (!Database.IDBStorageEnabled) {
  57666. this.callbackManifestChecked(true);
  57667. }
  57668. else {
  57669. this.checkManifestFile();
  57670. }
  57671. }
  57672. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  57673. get: function () {
  57674. return this._enableSceneOffline;
  57675. },
  57676. enumerable: true,
  57677. configurable: true
  57678. });
  57679. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  57680. get: function () {
  57681. return this._enableTexturesOffline;
  57682. },
  57683. enumerable: true,
  57684. configurable: true
  57685. });
  57686. Database.prototype.checkManifestFile = function () {
  57687. var _this = this;
  57688. var noManifestFile = function () {
  57689. _this._enableSceneOffline = false;
  57690. _this._enableTexturesOffline = false;
  57691. _this.callbackManifestChecked(false);
  57692. };
  57693. var timeStampUsed = false;
  57694. var manifestURL = this.currentSceneUrl + ".manifest";
  57695. var xhr = new XMLHttpRequest();
  57696. if (navigator.onLine) {
  57697. // Adding a timestamp to by-pass browsers' cache
  57698. timeStampUsed = true;
  57699. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  57700. }
  57701. xhr.open("GET", manifestURL, true);
  57702. xhr.addEventListener("load", function () {
  57703. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57704. try {
  57705. var manifestFile = JSON.parse(xhr.response);
  57706. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  57707. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  57708. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  57709. _this.manifestVersionFound = manifestFile.version;
  57710. }
  57711. if (_this.callbackManifestChecked) {
  57712. _this.callbackManifestChecked(true);
  57713. }
  57714. }
  57715. catch (ex) {
  57716. noManifestFile();
  57717. }
  57718. }
  57719. else {
  57720. noManifestFile();
  57721. }
  57722. }, false);
  57723. xhr.addEventListener("error", function (event) {
  57724. if (timeStampUsed) {
  57725. timeStampUsed = false;
  57726. // Let's retry without the timeStamp
  57727. // It could fail when coupled with HTML5 Offline API
  57728. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  57729. xhr.open("GET", retryManifestURL, true);
  57730. xhr.send();
  57731. }
  57732. else {
  57733. noManifestFile();
  57734. }
  57735. }, false);
  57736. try {
  57737. xhr.send();
  57738. }
  57739. catch (ex) {
  57740. BABYLON.Tools.Error("Error on XHR send request.");
  57741. this.callbackManifestChecked(false);
  57742. }
  57743. };
  57744. Database.prototype.openAsync = function (successCallback, errorCallback) {
  57745. var _this = this;
  57746. var handleError = function () {
  57747. _this.isSupported = false;
  57748. if (errorCallback)
  57749. errorCallback();
  57750. };
  57751. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  57752. // Your browser doesn't support IndexedDB
  57753. this.isSupported = false;
  57754. if (errorCallback)
  57755. errorCallback();
  57756. }
  57757. else {
  57758. // If the DB hasn't been opened or created yet
  57759. if (!this.db) {
  57760. this.hasReachedQuota = false;
  57761. this.isSupported = true;
  57762. var request = this.idbFactory.open("babylonjs", 1);
  57763. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  57764. request.onerror = function (event) {
  57765. handleError();
  57766. };
  57767. // executes when a version change transaction cannot complete due to other active transactions
  57768. request.onblocked = function (event) {
  57769. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  57770. handleError();
  57771. };
  57772. // DB has been opened successfully
  57773. request.onsuccess = function (event) {
  57774. _this.db = request.result;
  57775. successCallback();
  57776. };
  57777. // Initialization of the DB. Creating Scenes & Textures stores
  57778. request.onupgradeneeded = function (event) {
  57779. _this.db = (event.target).result;
  57780. if (_this.db) {
  57781. try {
  57782. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  57783. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  57784. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  57785. }
  57786. catch (ex) {
  57787. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  57788. handleError();
  57789. }
  57790. }
  57791. };
  57792. }
  57793. else {
  57794. if (successCallback)
  57795. successCallback();
  57796. }
  57797. }
  57798. };
  57799. Database.prototype.loadImageFromDB = function (url, image) {
  57800. var _this = this;
  57801. var completeURL = Database.ReturnFullUrlLocation(url);
  57802. var saveAndLoadImage = function () {
  57803. if (!_this.hasReachedQuota && _this.db !== null) {
  57804. // the texture is not yet in the DB, let's try to save it
  57805. _this._saveImageIntoDBAsync(completeURL, image);
  57806. }
  57807. else {
  57808. image.src = url;
  57809. }
  57810. };
  57811. if (!this.mustUpdateRessources) {
  57812. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  57813. }
  57814. else {
  57815. saveAndLoadImage();
  57816. }
  57817. };
  57818. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  57819. if (this.isSupported && this.db !== null) {
  57820. var texture;
  57821. var transaction = this.db.transaction(["textures"]);
  57822. transaction.onabort = function (event) {
  57823. image.src = url;
  57824. };
  57825. transaction.oncomplete = function (event) {
  57826. var blobTextureURL;
  57827. if (texture) {
  57828. var URL = window.URL || window.webkitURL;
  57829. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  57830. image.onerror = function () {
  57831. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  57832. image.src = url;
  57833. };
  57834. image.src = blobTextureURL;
  57835. }
  57836. else {
  57837. notInDBCallback();
  57838. }
  57839. };
  57840. var getRequest = transaction.objectStore("textures").get(url);
  57841. getRequest.onsuccess = function (event) {
  57842. texture = (event.target).result;
  57843. };
  57844. getRequest.onerror = function (event) {
  57845. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  57846. image.src = url;
  57847. };
  57848. }
  57849. else {
  57850. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57851. image.src = url;
  57852. }
  57853. };
  57854. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  57855. var _this = this;
  57856. if (this.isSupported) {
  57857. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  57858. var generateBlobUrl = function () {
  57859. var blobTextureURL;
  57860. if (blob) {
  57861. var URL = window.URL || window.webkitURL;
  57862. try {
  57863. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  57864. }
  57865. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  57866. catch (ex) {
  57867. blobTextureURL = URL.createObjectURL(blob);
  57868. }
  57869. }
  57870. if (blobTextureURL) {
  57871. image.src = blobTextureURL;
  57872. }
  57873. };
  57874. if (Database.IsUASupportingBlobStorage) {
  57875. var xhr = new XMLHttpRequest(), blob;
  57876. xhr.open("GET", url, true);
  57877. xhr.responseType = "blob";
  57878. xhr.addEventListener("load", function () {
  57879. if (xhr.status === 200 && _this.db) {
  57880. // Blob as response (XHR2)
  57881. blob = xhr.response;
  57882. var transaction = _this.db.transaction(["textures"], "readwrite");
  57883. // the transaction could abort because of a QuotaExceededError error
  57884. transaction.onabort = function (event) {
  57885. try {
  57886. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  57887. var srcElement = (event.srcElement || event.target);
  57888. var error = srcElement.error;
  57889. if (error && error.name === "QuotaExceededError") {
  57890. _this.hasReachedQuota = true;
  57891. }
  57892. }
  57893. catch (ex) { }
  57894. generateBlobUrl();
  57895. };
  57896. transaction.oncomplete = function (event) {
  57897. generateBlobUrl();
  57898. };
  57899. var newTexture = { textureUrl: url, data: blob };
  57900. try {
  57901. // Put the blob into the dabase
  57902. var addRequest = transaction.objectStore("textures").put(newTexture);
  57903. addRequest.onsuccess = function (event) {
  57904. };
  57905. addRequest.onerror = function (event) {
  57906. generateBlobUrl();
  57907. };
  57908. }
  57909. catch (ex) {
  57910. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  57911. if (ex.code === 25) {
  57912. Database.IsUASupportingBlobStorage = false;
  57913. }
  57914. image.src = url;
  57915. }
  57916. }
  57917. else {
  57918. image.src = url;
  57919. }
  57920. }, false);
  57921. xhr.addEventListener("error", function (event) {
  57922. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  57923. image.src = url;
  57924. }, false);
  57925. xhr.send();
  57926. }
  57927. else {
  57928. image.src = url;
  57929. }
  57930. }
  57931. else {
  57932. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57933. image.src = url;
  57934. }
  57935. };
  57936. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  57937. var _this = this;
  57938. var updateVersion = function () {
  57939. // the version is not yet in the DB or we need to update it
  57940. _this._saveVersionIntoDBAsync(url, versionLoaded);
  57941. };
  57942. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  57943. };
  57944. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  57945. var _this = this;
  57946. if (this.isSupported && this.db) {
  57947. var version;
  57948. try {
  57949. var transaction = this.db.transaction(["versions"]);
  57950. transaction.oncomplete = function (event) {
  57951. if (version) {
  57952. // If the version in the JSON file is > than the version in DB
  57953. if (_this.manifestVersionFound > version.data) {
  57954. _this.mustUpdateRessources = true;
  57955. updateInDBCallback();
  57956. }
  57957. else {
  57958. callback(version.data);
  57959. }
  57960. }
  57961. else {
  57962. _this.mustUpdateRessources = true;
  57963. updateInDBCallback();
  57964. }
  57965. };
  57966. transaction.onabort = function (event) {
  57967. callback(-1);
  57968. };
  57969. var getRequest = transaction.objectStore("versions").get(url);
  57970. getRequest.onsuccess = function (event) {
  57971. version = (event.target).result;
  57972. };
  57973. getRequest.onerror = function (event) {
  57974. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  57975. callback(-1);
  57976. };
  57977. }
  57978. catch (ex) {
  57979. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  57980. callback(-1);
  57981. }
  57982. }
  57983. else {
  57984. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57985. callback(-1);
  57986. }
  57987. };
  57988. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  57989. var _this = this;
  57990. if (this.isSupported && !this.hasReachedQuota && this.db) {
  57991. try {
  57992. // Open a transaction to the database
  57993. var transaction = this.db.transaction(["versions"], "readwrite");
  57994. // the transaction could abort because of a QuotaExceededError error
  57995. transaction.onabort = function (event) {
  57996. try {
  57997. var error = event.srcElement['error'];
  57998. if (error && error.name === "QuotaExceededError") {
  57999. _this.hasReachedQuota = true;
  58000. }
  58001. }
  58002. catch (ex) { }
  58003. callback(-1);
  58004. };
  58005. transaction.oncomplete = function (event) {
  58006. callback(_this.manifestVersionFound);
  58007. };
  58008. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58009. // Put the scene into the database
  58010. var addRequest = transaction.objectStore("versions").put(newVersion);
  58011. addRequest.onsuccess = function (event) {
  58012. };
  58013. addRequest.onerror = function (event) {
  58014. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58015. };
  58016. }
  58017. catch (ex) {
  58018. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58019. callback(-1);
  58020. }
  58021. }
  58022. else {
  58023. callback(-1);
  58024. }
  58025. };
  58026. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58027. var _this = this;
  58028. var completeUrl = Database.ReturnFullUrlLocation(url);
  58029. var saveAndLoadFile = function () {
  58030. // the scene is not yet in the DB, let's try to save it
  58031. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58032. };
  58033. this._checkVersionFromDB(completeUrl, function (version) {
  58034. if (version !== -1) {
  58035. if (!_this.mustUpdateRessources) {
  58036. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58037. }
  58038. else {
  58039. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58040. }
  58041. }
  58042. else {
  58043. if (errorCallback) {
  58044. errorCallback();
  58045. }
  58046. }
  58047. });
  58048. };
  58049. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58050. if (this.isSupported && this.db) {
  58051. var targetStore;
  58052. if (url.indexOf(".babylon") !== -1) {
  58053. targetStore = "scenes";
  58054. }
  58055. else {
  58056. targetStore = "textures";
  58057. }
  58058. var file;
  58059. var transaction = this.db.transaction([targetStore]);
  58060. transaction.oncomplete = function (event) {
  58061. if (file) {
  58062. callback(file.data);
  58063. }
  58064. else {
  58065. notInDBCallback();
  58066. }
  58067. };
  58068. transaction.onabort = function (event) {
  58069. notInDBCallback();
  58070. };
  58071. var getRequest = transaction.objectStore(targetStore).get(url);
  58072. getRequest.onsuccess = function (event) {
  58073. file = (event.target).result;
  58074. };
  58075. getRequest.onerror = function (event) {
  58076. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58077. notInDBCallback();
  58078. };
  58079. }
  58080. else {
  58081. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58082. callback();
  58083. }
  58084. };
  58085. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58086. var _this = this;
  58087. if (this.isSupported) {
  58088. var targetStore;
  58089. if (url.indexOf(".babylon") !== -1) {
  58090. targetStore = "scenes";
  58091. }
  58092. else {
  58093. targetStore = "textures";
  58094. }
  58095. // Create XHR
  58096. var xhr = new XMLHttpRequest();
  58097. var fileData;
  58098. xhr.open("GET", url, true);
  58099. if (useArrayBuffer) {
  58100. xhr.responseType = "arraybuffer";
  58101. }
  58102. if (progressCallback) {
  58103. xhr.onprogress = progressCallback;
  58104. }
  58105. xhr.addEventListener("load", function () {
  58106. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58107. // Blob as response (XHR2)
  58108. //fileData = xhr.responseText;
  58109. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58110. if (!_this.hasReachedQuota && _this.db) {
  58111. // Open a transaction to the database
  58112. var transaction = _this.db.transaction([targetStore], "readwrite");
  58113. // the transaction could abort because of a QuotaExceededError error
  58114. transaction.onabort = function (event) {
  58115. try {
  58116. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58117. var error = event.srcElement['error'];
  58118. if (error && error.name === "QuotaExceededError") {
  58119. _this.hasReachedQuota = true;
  58120. }
  58121. }
  58122. catch (ex) { }
  58123. callback(fileData);
  58124. };
  58125. transaction.oncomplete = function (event) {
  58126. callback(fileData);
  58127. };
  58128. var newFile;
  58129. if (targetStore === "scenes") {
  58130. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58131. }
  58132. else {
  58133. newFile = { textureUrl: url, data: fileData };
  58134. }
  58135. try {
  58136. // Put the scene into the database
  58137. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58138. addRequest.onsuccess = function (event) {
  58139. };
  58140. addRequest.onerror = function (event) {
  58141. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58142. };
  58143. }
  58144. catch (ex) {
  58145. callback(fileData);
  58146. }
  58147. }
  58148. else {
  58149. callback(fileData);
  58150. }
  58151. }
  58152. else {
  58153. callback();
  58154. }
  58155. }, false);
  58156. xhr.addEventListener("error", function (event) {
  58157. BABYLON.Tools.Error("error on XHR request.");
  58158. callback();
  58159. }, false);
  58160. xhr.send();
  58161. }
  58162. else {
  58163. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58164. callback();
  58165. }
  58166. };
  58167. Database.IsUASupportingBlobStorage = true;
  58168. Database.IDBStorageEnabled = true;
  58169. Database.parseURL = function (url) {
  58170. var a = document.createElement('a');
  58171. a.href = url;
  58172. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58173. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58174. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58175. return absLocation;
  58176. };
  58177. Database.ReturnFullUrlLocation = function (url) {
  58178. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58179. return (Database.parseURL(window.location.href) + url);
  58180. }
  58181. else {
  58182. return url;
  58183. }
  58184. };
  58185. return Database;
  58186. }());
  58187. BABYLON.Database = Database;
  58188. })(BABYLON || (BABYLON = {}));
  58189. //# sourceMappingURL=babylon.database.js.map
  58190. var BABYLON;
  58191. (function (BABYLON) {
  58192. var FresnelParameters = /** @class */ (function () {
  58193. function FresnelParameters() {
  58194. this._isEnabled = true;
  58195. this.leftColor = BABYLON.Color3.White();
  58196. this.rightColor = BABYLON.Color3.Black();
  58197. this.bias = 0;
  58198. this.power = 1;
  58199. }
  58200. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58201. get: function () {
  58202. return this._isEnabled;
  58203. },
  58204. set: function (value) {
  58205. if (this._isEnabled === value) {
  58206. return;
  58207. }
  58208. this._isEnabled = value;
  58209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  58210. },
  58211. enumerable: true,
  58212. configurable: true
  58213. });
  58214. FresnelParameters.prototype.clone = function () {
  58215. var newFresnelParameters = new FresnelParameters();
  58216. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58217. return newFresnelParameters;
  58218. };
  58219. FresnelParameters.prototype.serialize = function () {
  58220. var serializationObject = {};
  58221. serializationObject.isEnabled = this.isEnabled;
  58222. serializationObject.leftColor = this.leftColor;
  58223. serializationObject.rightColor = this.rightColor;
  58224. serializationObject.bias = this.bias;
  58225. serializationObject.power = this.power;
  58226. return serializationObject;
  58227. };
  58228. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58229. var fresnelParameters = new FresnelParameters();
  58230. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58231. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58232. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58233. fresnelParameters.bias = parsedFresnelParameters.bias;
  58234. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58235. return fresnelParameters;
  58236. };
  58237. return FresnelParameters;
  58238. }());
  58239. BABYLON.FresnelParameters = FresnelParameters;
  58240. })(BABYLON || (BABYLON = {}));
  58241. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58242. var BABYLON;
  58243. (function (BABYLON) {
  58244. var MultiMaterial = /** @class */ (function (_super) {
  58245. __extends(MultiMaterial, _super);
  58246. function MultiMaterial(name, scene) {
  58247. var _this = _super.call(this, name, scene, true) || this;
  58248. scene.multiMaterials.push(_this);
  58249. _this.subMaterials = new Array();
  58250. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58251. return _this;
  58252. }
  58253. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58254. get: function () {
  58255. return this._subMaterials;
  58256. },
  58257. set: function (value) {
  58258. this._subMaterials = value;
  58259. this._hookArray(value);
  58260. },
  58261. enumerable: true,
  58262. configurable: true
  58263. });
  58264. MultiMaterial.prototype._hookArray = function (array) {
  58265. var _this = this;
  58266. var oldPush = array.push;
  58267. array.push = function () {
  58268. var items = [];
  58269. for (var _i = 0; _i < arguments.length; _i++) {
  58270. items[_i] = arguments[_i];
  58271. }
  58272. var result = oldPush.apply(array, items);
  58273. _this._markAllSubMeshesAsTexturesDirty();
  58274. return result;
  58275. };
  58276. var oldSplice = array.splice;
  58277. array.splice = function (index, deleteCount) {
  58278. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58279. _this._markAllSubMeshesAsTexturesDirty();
  58280. return deleted;
  58281. };
  58282. };
  58283. // Properties
  58284. MultiMaterial.prototype.getSubMaterial = function (index) {
  58285. if (index < 0 || index >= this.subMaterials.length) {
  58286. return this.getScene().defaultMaterial;
  58287. }
  58288. return this.subMaterials[index];
  58289. };
  58290. MultiMaterial.prototype.getActiveTextures = function () {
  58291. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58292. if (subMaterial) {
  58293. return subMaterial.getActiveTextures();
  58294. }
  58295. else {
  58296. return [];
  58297. }
  58298. }));
  58299. var _a;
  58300. };
  58301. // Methods
  58302. MultiMaterial.prototype.getClassName = function () {
  58303. return "MultiMaterial";
  58304. };
  58305. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58306. for (var index = 0; index < this.subMaterials.length; index++) {
  58307. var subMaterial = this.subMaterials[index];
  58308. if (subMaterial) {
  58309. if (subMaterial.storeEffectOnSubMeshes) {
  58310. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58311. return false;
  58312. }
  58313. continue;
  58314. }
  58315. if (!subMaterial.isReady(mesh)) {
  58316. return false;
  58317. }
  58318. }
  58319. }
  58320. return true;
  58321. };
  58322. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58323. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58324. for (var index = 0; index < this.subMaterials.length; index++) {
  58325. var subMaterial = null;
  58326. var current = this.subMaterials[index];
  58327. if (cloneChildren && current) {
  58328. subMaterial = current.clone(name + "-" + current.name);
  58329. }
  58330. else {
  58331. subMaterial = this.subMaterials[index];
  58332. }
  58333. newMultiMaterial.subMaterials.push(subMaterial);
  58334. }
  58335. return newMultiMaterial;
  58336. };
  58337. MultiMaterial.prototype.serialize = function () {
  58338. var serializationObject = {};
  58339. serializationObject.name = this.name;
  58340. serializationObject.id = this.id;
  58341. if (BABYLON.Tags) {
  58342. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58343. }
  58344. serializationObject.materials = [];
  58345. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58346. var subMat = this.subMaterials[matIndex];
  58347. if (subMat) {
  58348. serializationObject.materials.push(subMat.id);
  58349. }
  58350. else {
  58351. serializationObject.materials.push(null);
  58352. }
  58353. }
  58354. return serializationObject;
  58355. };
  58356. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58357. var scene = this.getScene();
  58358. if (!scene) {
  58359. return;
  58360. }
  58361. var index = scene.multiMaterials.indexOf(this);
  58362. if (index >= 0) {
  58363. scene.multiMaterials.splice(index, 1);
  58364. }
  58365. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58366. };
  58367. return MultiMaterial;
  58368. }(BABYLON.Material));
  58369. BABYLON.MultiMaterial = MultiMaterial;
  58370. })(BABYLON || (BABYLON = {}));
  58371. //# sourceMappingURL=babylon.multiMaterial.js.map
  58372. var BABYLON;
  58373. (function (BABYLON) {
  58374. var FreeCameraTouchInput = /** @class */ (function () {
  58375. function FreeCameraTouchInput() {
  58376. this._offsetX = null;
  58377. this._offsetY = null;
  58378. this._pointerPressed = new Array();
  58379. this.touchAngularSensibility = 200000.0;
  58380. this.touchMoveSensibility = 250.0;
  58381. }
  58382. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58383. var _this = this;
  58384. var previousPosition = null;
  58385. if (this._pointerInput === undefined) {
  58386. this._onLostFocus = function (evt) {
  58387. _this._offsetX = null;
  58388. _this._offsetY = null;
  58389. };
  58390. this._pointerInput = function (p, s) {
  58391. var evt = p.event;
  58392. if (evt.pointerType === "mouse") {
  58393. return;
  58394. }
  58395. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58396. if (!noPreventDefault) {
  58397. evt.preventDefault();
  58398. }
  58399. _this._pointerPressed.push(evt.pointerId);
  58400. if (_this._pointerPressed.length !== 1) {
  58401. return;
  58402. }
  58403. previousPosition = {
  58404. x: evt.clientX,
  58405. y: evt.clientY
  58406. };
  58407. }
  58408. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58409. if (!noPreventDefault) {
  58410. evt.preventDefault();
  58411. }
  58412. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58413. if (index === -1) {
  58414. return;
  58415. }
  58416. _this._pointerPressed.splice(index, 1);
  58417. if (index != 0) {
  58418. return;
  58419. }
  58420. previousPosition = null;
  58421. _this._offsetX = null;
  58422. _this._offsetY = null;
  58423. }
  58424. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58425. if (!noPreventDefault) {
  58426. evt.preventDefault();
  58427. }
  58428. if (!previousPosition) {
  58429. return;
  58430. }
  58431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58432. if (index != 0) {
  58433. return;
  58434. }
  58435. _this._offsetX = evt.clientX - previousPosition.x;
  58436. _this._offsetY = -(evt.clientY - previousPosition.y);
  58437. }
  58438. };
  58439. }
  58440. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58441. if (this._onLostFocus) {
  58442. element.addEventListener("blur", this._onLostFocus);
  58443. }
  58444. };
  58445. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58446. if (this._pointerInput && element) {
  58447. if (this._observer) {
  58448. this.camera.getScene().onPointerObservable.remove(this._observer);
  58449. this._observer = null;
  58450. }
  58451. if (this._onLostFocus) {
  58452. element.removeEventListener("blur", this._onLostFocus);
  58453. this._onLostFocus = null;
  58454. }
  58455. this._pointerPressed = [];
  58456. this._offsetX = null;
  58457. this._offsetY = null;
  58458. }
  58459. };
  58460. FreeCameraTouchInput.prototype.checkInputs = function () {
  58461. if (this._offsetX && this._offsetY) {
  58462. var camera = this.camera;
  58463. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58464. if (this._pointerPressed.length > 1) {
  58465. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58466. }
  58467. else {
  58468. var speed = camera._computeLocalCameraSpeed();
  58469. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  58470. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  58471. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  58472. }
  58473. }
  58474. };
  58475. FreeCameraTouchInput.prototype.getClassName = function () {
  58476. return "FreeCameraTouchInput";
  58477. };
  58478. FreeCameraTouchInput.prototype.getSimpleName = function () {
  58479. return "touch";
  58480. };
  58481. __decorate([
  58482. BABYLON.serialize()
  58483. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  58484. __decorate([
  58485. BABYLON.serialize()
  58486. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  58487. return FreeCameraTouchInput;
  58488. }());
  58489. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  58490. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  58491. })(BABYLON || (BABYLON = {}));
  58492. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  58493. var BABYLON;
  58494. (function (BABYLON) {
  58495. // We're mainly based on the logic defined into the FreeCamera code
  58496. var TouchCamera = /** @class */ (function (_super) {
  58497. __extends(TouchCamera, _super);
  58498. //-- end properties for backward compatibility for inputs
  58499. function TouchCamera(name, position, scene) {
  58500. var _this = _super.call(this, name, position, scene) || this;
  58501. _this.inputs.addTouch();
  58502. _this._setupInputs();
  58503. return _this;
  58504. }
  58505. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  58506. //-- Begin properties for backward compatibility for inputs
  58507. get: function () {
  58508. var touch = this.inputs.attached["touch"];
  58509. if (touch)
  58510. return touch.touchAngularSensibility;
  58511. return 0;
  58512. },
  58513. set: function (value) {
  58514. var touch = this.inputs.attached["touch"];
  58515. if (touch)
  58516. touch.touchAngularSensibility = value;
  58517. },
  58518. enumerable: true,
  58519. configurable: true
  58520. });
  58521. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  58522. get: function () {
  58523. var touch = this.inputs.attached["touch"];
  58524. if (touch)
  58525. return touch.touchMoveSensibility;
  58526. return 0;
  58527. },
  58528. set: function (value) {
  58529. var touch = this.inputs.attached["touch"];
  58530. if (touch)
  58531. touch.touchMoveSensibility = value;
  58532. },
  58533. enumerable: true,
  58534. configurable: true
  58535. });
  58536. TouchCamera.prototype.getClassName = function () {
  58537. return "TouchCamera";
  58538. };
  58539. TouchCamera.prototype._setupInputs = function () {
  58540. var mouse = this.inputs.attached["mouse"];
  58541. if (mouse) {
  58542. mouse.touchEnabled = false;
  58543. }
  58544. };
  58545. return TouchCamera;
  58546. }(BABYLON.FreeCamera));
  58547. BABYLON.TouchCamera = TouchCamera;
  58548. })(BABYLON || (BABYLON = {}));
  58549. //# sourceMappingURL=babylon.touchCamera.js.map
  58550. var BABYLON;
  58551. (function (BABYLON) {
  58552. var ProceduralTexture = /** @class */ (function (_super) {
  58553. __extends(ProceduralTexture, _super);
  58554. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  58555. if (fallbackTexture === void 0) { fallbackTexture = null; }
  58556. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58557. if (isCube === void 0) { isCube = false; }
  58558. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58559. _this.isCube = isCube;
  58560. _this.isEnabled = true;
  58561. _this._currentRefreshId = -1;
  58562. _this._refreshRate = 1;
  58563. _this._vertexBuffers = {};
  58564. _this._uniforms = new Array();
  58565. _this._samplers = new Array();
  58566. _this._textures = {};
  58567. _this._floats = {};
  58568. _this._floatsArrays = {};
  58569. _this._colors3 = {};
  58570. _this._colors4 = {};
  58571. _this._vectors2 = {};
  58572. _this._vectors3 = {};
  58573. _this._matrices = {};
  58574. _this._fallbackTextureUsed = false;
  58575. scene._proceduralTextures.push(_this);
  58576. _this._engine = scene.getEngine();
  58577. _this.name = name;
  58578. _this.isRenderTarget = true;
  58579. _this._size = size;
  58580. _this._generateMipMaps = generateMipMaps;
  58581. _this.setFragment(fragment);
  58582. _this._fallbackTexture = fallbackTexture;
  58583. if (isCube) {
  58584. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  58585. _this.setFloat("face", 0);
  58586. }
  58587. else {
  58588. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  58589. }
  58590. // VBO
  58591. var vertices = [];
  58592. vertices.push(1, 1);
  58593. vertices.push(-1, 1);
  58594. vertices.push(-1, -1);
  58595. vertices.push(1, -1);
  58596. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58597. _this._createIndexBuffer();
  58598. return _this;
  58599. }
  58600. ProceduralTexture.prototype._createIndexBuffer = function () {
  58601. var engine = this._engine;
  58602. // Indices
  58603. var indices = [];
  58604. indices.push(0);
  58605. indices.push(1);
  58606. indices.push(2);
  58607. indices.push(0);
  58608. indices.push(2);
  58609. indices.push(3);
  58610. this._indexBuffer = engine.createIndexBuffer(indices);
  58611. };
  58612. ProceduralTexture.prototype._rebuild = function () {
  58613. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58614. if (vb) {
  58615. vb._rebuild();
  58616. }
  58617. this._createIndexBuffer();
  58618. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58619. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58620. }
  58621. };
  58622. ProceduralTexture.prototype.reset = function () {
  58623. if (this._effect === undefined) {
  58624. return;
  58625. }
  58626. var engine = this._engine;
  58627. engine._releaseEffect(this._effect);
  58628. };
  58629. ProceduralTexture.prototype.isReady = function () {
  58630. var _this = this;
  58631. var engine = this._engine;
  58632. var shaders;
  58633. if (!this._fragment) {
  58634. return false;
  58635. }
  58636. if (this._fallbackTextureUsed) {
  58637. return true;
  58638. }
  58639. if (this._fragment.fragmentElement !== undefined) {
  58640. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  58641. }
  58642. else {
  58643. shaders = { vertex: "procedural", fragment: this._fragment };
  58644. }
  58645. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  58646. _this.releaseInternalTexture();
  58647. if (_this._fallbackTexture) {
  58648. _this._texture = _this._fallbackTexture._texture;
  58649. if (_this._texture) {
  58650. _this._texture.incrementReferences();
  58651. }
  58652. }
  58653. _this._fallbackTextureUsed = true;
  58654. });
  58655. return this._effect.isReady();
  58656. };
  58657. ProceduralTexture.prototype.resetRefreshCounter = function () {
  58658. this._currentRefreshId = -1;
  58659. };
  58660. ProceduralTexture.prototype.setFragment = function (fragment) {
  58661. this._fragment = fragment;
  58662. };
  58663. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  58664. get: function () {
  58665. return this._refreshRate;
  58666. },
  58667. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58668. set: function (value) {
  58669. this._refreshRate = value;
  58670. this.resetRefreshCounter();
  58671. },
  58672. enumerable: true,
  58673. configurable: true
  58674. });
  58675. ProceduralTexture.prototype._shouldRender = function () {
  58676. if (!this.isEnabled || !this.isReady() || !this._texture) {
  58677. return false;
  58678. }
  58679. if (this._fallbackTextureUsed) {
  58680. return false;
  58681. }
  58682. if (this._currentRefreshId === -1) {
  58683. this._currentRefreshId = 1;
  58684. return true;
  58685. }
  58686. if (this.refreshRate === this._currentRefreshId) {
  58687. this._currentRefreshId = 1;
  58688. return true;
  58689. }
  58690. this._currentRefreshId++;
  58691. return false;
  58692. };
  58693. ProceduralTexture.prototype.getRenderSize = function () {
  58694. return this._size;
  58695. };
  58696. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  58697. if (this._fallbackTextureUsed) {
  58698. return;
  58699. }
  58700. this.releaseInternalTexture();
  58701. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  58702. };
  58703. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  58704. if (this._uniforms.indexOf(uniformName) === -1) {
  58705. this._uniforms.push(uniformName);
  58706. }
  58707. };
  58708. ProceduralTexture.prototype.setTexture = function (name, texture) {
  58709. if (this._samplers.indexOf(name) === -1) {
  58710. this._samplers.push(name);
  58711. }
  58712. this._textures[name] = texture;
  58713. return this;
  58714. };
  58715. ProceduralTexture.prototype.setFloat = function (name, value) {
  58716. this._checkUniform(name);
  58717. this._floats[name] = value;
  58718. return this;
  58719. };
  58720. ProceduralTexture.prototype.setFloats = function (name, value) {
  58721. this._checkUniform(name);
  58722. this._floatsArrays[name] = value;
  58723. return this;
  58724. };
  58725. ProceduralTexture.prototype.setColor3 = function (name, value) {
  58726. this._checkUniform(name);
  58727. this._colors3[name] = value;
  58728. return this;
  58729. };
  58730. ProceduralTexture.prototype.setColor4 = function (name, value) {
  58731. this._checkUniform(name);
  58732. this._colors4[name] = value;
  58733. return this;
  58734. };
  58735. ProceduralTexture.prototype.setVector2 = function (name, value) {
  58736. this._checkUniform(name);
  58737. this._vectors2[name] = value;
  58738. return this;
  58739. };
  58740. ProceduralTexture.prototype.setVector3 = function (name, value) {
  58741. this._checkUniform(name);
  58742. this._vectors3[name] = value;
  58743. return this;
  58744. };
  58745. ProceduralTexture.prototype.setMatrix = function (name, value) {
  58746. this._checkUniform(name);
  58747. this._matrices[name] = value;
  58748. return this;
  58749. };
  58750. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58751. var scene = this.getScene();
  58752. if (!scene) {
  58753. return;
  58754. }
  58755. var engine = this._engine;
  58756. // Render
  58757. engine.enableEffect(this._effect);
  58758. engine.setState(false);
  58759. // Texture
  58760. for (var name in this._textures) {
  58761. this._effect.setTexture(name, this._textures[name]);
  58762. }
  58763. // Float
  58764. for (name in this._floats) {
  58765. this._effect.setFloat(name, this._floats[name]);
  58766. }
  58767. // Floats
  58768. for (name in this._floatsArrays) {
  58769. this._effect.setArray(name, this._floatsArrays[name]);
  58770. }
  58771. // Color3
  58772. for (name in this._colors3) {
  58773. this._effect.setColor3(name, this._colors3[name]);
  58774. }
  58775. // Color4
  58776. for (name in this._colors4) {
  58777. var color = this._colors4[name];
  58778. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58779. }
  58780. // Vector2
  58781. for (name in this._vectors2) {
  58782. this._effect.setVector2(name, this._vectors2[name]);
  58783. }
  58784. // Vector3
  58785. for (name in this._vectors3) {
  58786. this._effect.setVector3(name, this._vectors3[name]);
  58787. }
  58788. // Matrix
  58789. for (name in this._matrices) {
  58790. this._effect.setMatrix(name, this._matrices[name]);
  58791. }
  58792. if (!this._texture) {
  58793. return;
  58794. }
  58795. if (this.isCube) {
  58796. for (var face = 0; face < 6; face++) {
  58797. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  58798. // VBOs
  58799. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58800. this._effect.setFloat("face", face);
  58801. // Clear
  58802. engine.clear(scene.clearColor, true, true, true);
  58803. // Draw order
  58804. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58805. // Mipmaps
  58806. if (face === 5) {
  58807. engine.generateMipMapsForCubemap(this._texture);
  58808. }
  58809. }
  58810. }
  58811. else {
  58812. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  58813. // VBOs
  58814. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58815. // Clear
  58816. engine.clear(scene.clearColor, true, true, true);
  58817. // Draw order
  58818. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58819. }
  58820. // Unbind
  58821. engine.unBindFramebuffer(this._texture, this.isCube);
  58822. if (this.onGenerated) {
  58823. this.onGenerated();
  58824. }
  58825. };
  58826. ProceduralTexture.prototype.clone = function () {
  58827. var textureSize = this.getSize();
  58828. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  58829. // Base texture
  58830. newTexture.hasAlpha = this.hasAlpha;
  58831. newTexture.level = this.level;
  58832. // RenderTarget Texture
  58833. newTexture.coordinatesMode = this.coordinatesMode;
  58834. return newTexture;
  58835. };
  58836. ProceduralTexture.prototype.dispose = function () {
  58837. var scene = this.getScene();
  58838. if (!scene) {
  58839. return;
  58840. }
  58841. var index = scene._proceduralTextures.indexOf(this);
  58842. if (index >= 0) {
  58843. scene._proceduralTextures.splice(index, 1);
  58844. }
  58845. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58846. if (vertexBuffer) {
  58847. vertexBuffer.dispose();
  58848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58849. }
  58850. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  58851. this._indexBuffer = null;
  58852. }
  58853. _super.prototype.dispose.call(this);
  58854. };
  58855. return ProceduralTexture;
  58856. }(BABYLON.Texture));
  58857. BABYLON.ProceduralTexture = ProceduralTexture;
  58858. })(BABYLON || (BABYLON = {}));
  58859. //# sourceMappingURL=babylon.proceduralTexture.js.map
  58860. var BABYLON;
  58861. (function (BABYLON) {
  58862. var CustomProceduralTexture = /** @class */ (function (_super) {
  58863. __extends(CustomProceduralTexture, _super);
  58864. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  58865. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  58866. _this._animate = true;
  58867. _this._time = 0;
  58868. _this._texturePath = texturePath;
  58869. //Try to load json
  58870. _this.loadJson(texturePath);
  58871. _this.refreshRate = 1;
  58872. return _this;
  58873. }
  58874. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  58875. var _this = this;
  58876. var noConfigFile = function () {
  58877. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  58878. try {
  58879. _this.setFragment(_this._texturePath);
  58880. }
  58881. catch (ex) {
  58882. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  58883. }
  58884. };
  58885. var configFileUrl = jsonUrl + "/config.json";
  58886. var xhr = new XMLHttpRequest();
  58887. xhr.open("GET", configFileUrl, true);
  58888. xhr.addEventListener("load", function () {
  58889. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58890. try {
  58891. _this._config = JSON.parse(xhr.response);
  58892. _this.updateShaderUniforms();
  58893. _this.updateTextures();
  58894. _this.setFragment(_this._texturePath + "/custom");
  58895. _this._animate = _this._config.animate;
  58896. _this.refreshRate = _this._config.refreshrate;
  58897. }
  58898. catch (ex) {
  58899. noConfigFile();
  58900. }
  58901. }
  58902. else {
  58903. noConfigFile();
  58904. }
  58905. }, false);
  58906. xhr.addEventListener("error", function () {
  58907. noConfigFile();
  58908. }, false);
  58909. try {
  58910. xhr.send();
  58911. }
  58912. catch (ex) {
  58913. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  58914. }
  58915. };
  58916. CustomProceduralTexture.prototype.isReady = function () {
  58917. if (!_super.prototype.isReady.call(this)) {
  58918. return false;
  58919. }
  58920. for (var name in this._textures) {
  58921. var texture = this._textures[name];
  58922. if (!texture.isReady()) {
  58923. return false;
  58924. }
  58925. }
  58926. return true;
  58927. };
  58928. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58929. var scene = this.getScene();
  58930. if (this._animate && scene) {
  58931. this._time += scene.getAnimationRatio() * 0.03;
  58932. this.updateShaderUniforms();
  58933. }
  58934. _super.prototype.render.call(this, useCameraPostProcess);
  58935. };
  58936. CustomProceduralTexture.prototype.updateTextures = function () {
  58937. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  58938. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  58939. }
  58940. };
  58941. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  58942. if (this._config) {
  58943. for (var j = 0; j < this._config.uniforms.length; j++) {
  58944. var uniform = this._config.uniforms[j];
  58945. switch (uniform.type) {
  58946. case "float":
  58947. this.setFloat(uniform.name, uniform.value);
  58948. break;
  58949. case "color3":
  58950. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  58951. break;
  58952. case "color4":
  58953. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  58954. break;
  58955. case "vector2":
  58956. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  58957. break;
  58958. case "vector3":
  58959. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  58960. break;
  58961. }
  58962. }
  58963. }
  58964. this.setFloat("time", this._time);
  58965. };
  58966. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  58967. get: function () {
  58968. return this._animate;
  58969. },
  58970. set: function (value) {
  58971. this._animate = value;
  58972. },
  58973. enumerable: true,
  58974. configurable: true
  58975. });
  58976. return CustomProceduralTexture;
  58977. }(BABYLON.ProceduralTexture));
  58978. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  58979. })(BABYLON || (BABYLON = {}));
  58980. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  58981. var BABYLON;
  58982. (function (BABYLON) {
  58983. var FreeCameraGamepadInput = /** @class */ (function () {
  58984. function FreeCameraGamepadInput() {
  58985. this.gamepadAngularSensibility = 200;
  58986. this.gamepadMoveSensibility = 40;
  58987. // private members
  58988. this._cameraTransform = BABYLON.Matrix.Identity();
  58989. this._deltaTransform = BABYLON.Vector3.Zero();
  58990. this._vector3 = BABYLON.Vector3.Zero();
  58991. this._vector2 = BABYLON.Vector2.Zero();
  58992. }
  58993. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  58994. var _this = this;
  58995. var manager = this.camera.getScene().gamepadManager;
  58996. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  58997. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  58998. // prioritize XBOX gamepads.
  58999. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59000. _this.gamepad = gamepad;
  59001. }
  59002. }
  59003. });
  59004. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59005. if (_this.gamepad === gamepad) {
  59006. _this.gamepad = null;
  59007. }
  59008. });
  59009. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59010. };
  59011. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59012. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59013. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59014. this.gamepad = null;
  59015. };
  59016. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59017. if (this.gamepad && this.gamepad.leftStick) {
  59018. var camera = this.camera;
  59019. var LSValues = this.gamepad.leftStick;
  59020. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59021. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59022. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59023. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59024. var RSValues = this.gamepad.rightStick;
  59025. if (RSValues) {
  59026. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59027. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59028. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59029. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59030. }
  59031. else {
  59032. RSValues = { x: 0, y: 0 };
  59033. }
  59034. if (!camera.rotationQuaternion) {
  59035. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59036. }
  59037. else {
  59038. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59039. }
  59040. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59041. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59042. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59043. camera.cameraDirection.addInPlace(this._deltaTransform);
  59044. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59045. camera.cameraRotation.addInPlace(this._vector2);
  59046. }
  59047. };
  59048. FreeCameraGamepadInput.prototype.getClassName = function () {
  59049. return "FreeCameraGamepadInput";
  59050. };
  59051. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59052. return "gamepad";
  59053. };
  59054. __decorate([
  59055. BABYLON.serialize()
  59056. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59057. __decorate([
  59058. BABYLON.serialize()
  59059. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59060. return FreeCameraGamepadInput;
  59061. }());
  59062. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59063. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59064. })(BABYLON || (BABYLON = {}));
  59065. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59066. var BABYLON;
  59067. (function (BABYLON) {
  59068. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59069. function ArcRotateCameraGamepadInput() {
  59070. this.gamepadRotationSensibility = 80;
  59071. this.gamepadMoveSensibility = 40;
  59072. }
  59073. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59074. var _this = this;
  59075. var manager = this.camera.getScene().gamepadManager;
  59076. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59077. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59078. // prioritize XBOX gamepads.
  59079. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59080. _this.gamepad = gamepad;
  59081. }
  59082. }
  59083. });
  59084. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59085. if (_this.gamepad === gamepad) {
  59086. _this.gamepad = null;
  59087. }
  59088. });
  59089. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59090. };
  59091. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59092. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59093. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59094. this.gamepad = null;
  59095. };
  59096. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59097. if (this.gamepad) {
  59098. var camera = this.camera;
  59099. var RSValues = this.gamepad.rightStick;
  59100. if (RSValues) {
  59101. if (RSValues.x != 0) {
  59102. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59103. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59104. camera.inertialAlphaOffset += normalizedRX;
  59105. }
  59106. }
  59107. if (RSValues.y != 0) {
  59108. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59109. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59110. camera.inertialBetaOffset += normalizedRY;
  59111. }
  59112. }
  59113. }
  59114. var LSValues = this.gamepad.leftStick;
  59115. if (LSValues && LSValues.y != 0) {
  59116. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59117. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59118. this.camera.inertialRadiusOffset -= normalizedLY;
  59119. }
  59120. }
  59121. }
  59122. };
  59123. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59124. return "ArcRotateCameraGamepadInput";
  59125. };
  59126. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59127. return "gamepad";
  59128. };
  59129. __decorate([
  59130. BABYLON.serialize()
  59131. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59132. __decorate([
  59133. BABYLON.serialize()
  59134. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59135. return ArcRotateCameraGamepadInput;
  59136. }());
  59137. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59138. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59139. })(BABYLON || (BABYLON = {}));
  59140. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59141. var BABYLON;
  59142. (function (BABYLON) {
  59143. var GamepadManager = /** @class */ (function () {
  59144. function GamepadManager(_scene) {
  59145. var _this = this;
  59146. this._scene = _scene;
  59147. this._babylonGamepads = [];
  59148. this._oneGamepadConnected = false;
  59149. this._isMonitoring = false;
  59150. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59151. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59152. this._gamepadEventSupported = false;
  59153. }
  59154. else {
  59155. this._gamepadEventSupported = 'GamepadEvent' in window;
  59156. this._gamepadSupport = (navigator.getGamepads ||
  59157. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59158. }
  59159. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59160. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59161. for (var i in _this._babylonGamepads) {
  59162. var gamepad = _this._babylonGamepads[i];
  59163. if (gamepad && gamepad._isConnected) {
  59164. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59165. }
  59166. }
  59167. });
  59168. this._onGamepadConnectedEvent = function (evt) {
  59169. var gamepad = evt.gamepad;
  59170. if (gamepad.index in _this._babylonGamepads) {
  59171. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59172. return;
  59173. }
  59174. }
  59175. var newGamepad;
  59176. if (_this._babylonGamepads[gamepad.index]) {
  59177. newGamepad = _this._babylonGamepads[gamepad.index];
  59178. newGamepad.browserGamepad = gamepad;
  59179. newGamepad._isConnected = true;
  59180. }
  59181. else {
  59182. newGamepad = _this._addNewGamepad(gamepad);
  59183. }
  59184. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59185. _this._startMonitoringGamepads();
  59186. };
  59187. this._onGamepadDisconnectedEvent = function (evt) {
  59188. var gamepad = evt.gamepad;
  59189. // Remove the gamepad from the list of gamepads to monitor.
  59190. for (var i in _this._babylonGamepads) {
  59191. if (_this._babylonGamepads[i].index === gamepad.index) {
  59192. var disconnectedGamepad = _this._babylonGamepads[i];
  59193. disconnectedGamepad._isConnected = false;
  59194. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59195. break;
  59196. }
  59197. }
  59198. };
  59199. if (this._gamepadSupport) {
  59200. //first add already-connected gamepads
  59201. this._updateGamepadObjects();
  59202. if (this._babylonGamepads.length) {
  59203. this._startMonitoringGamepads();
  59204. }
  59205. // Checking if the gamepad connected event is supported (like in Firefox)
  59206. if (this._gamepadEventSupported) {
  59207. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59208. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59209. }
  59210. else {
  59211. this._startMonitoringGamepads();
  59212. }
  59213. }
  59214. }
  59215. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59216. get: function () {
  59217. return this._babylonGamepads;
  59218. },
  59219. enumerable: true,
  59220. configurable: true
  59221. });
  59222. GamepadManager.prototype.getGamepadByType = function (type) {
  59223. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59224. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59225. var gamepad = _a[_i];
  59226. if (gamepad && gamepad.type === type) {
  59227. return gamepad;
  59228. }
  59229. }
  59230. return null;
  59231. };
  59232. GamepadManager.prototype.dispose = function () {
  59233. if (this._gamepadEventSupported) {
  59234. if (this._onGamepadConnectedEvent) {
  59235. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59236. }
  59237. if (this._onGamepadDisconnectedEvent) {
  59238. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59239. }
  59240. this._onGamepadConnectedEvent = null;
  59241. this._onGamepadDisconnectedEvent = null;
  59242. }
  59243. this._babylonGamepads.forEach(function (gamepad) {
  59244. gamepad.dispose();
  59245. });
  59246. this.onGamepadConnectedObservable.clear();
  59247. this.onGamepadDisconnectedObservable.clear();
  59248. this._oneGamepadConnected = false;
  59249. this._stopMonitoringGamepads();
  59250. this._babylonGamepads = [];
  59251. };
  59252. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59253. if (!this._oneGamepadConnected) {
  59254. this._oneGamepadConnected = true;
  59255. }
  59256. var newGamepad;
  59257. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59258. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59259. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59260. }
  59261. else if (gamepad.pose) {
  59262. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59263. }
  59264. else {
  59265. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59266. }
  59267. this._babylonGamepads[newGamepad.index] = newGamepad;
  59268. return newGamepad;
  59269. };
  59270. GamepadManager.prototype._startMonitoringGamepads = function () {
  59271. if (!this._isMonitoring) {
  59272. this._isMonitoring = true;
  59273. //back-comp
  59274. if (!this._scene) {
  59275. this._checkGamepadsStatus();
  59276. }
  59277. }
  59278. };
  59279. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59280. this._isMonitoring = false;
  59281. };
  59282. GamepadManager.prototype._checkGamepadsStatus = function () {
  59283. var _this = this;
  59284. // Hack to be compatible Chrome
  59285. this._updateGamepadObjects();
  59286. for (var i in this._babylonGamepads) {
  59287. var gamepad = this._babylonGamepads[i];
  59288. if (!gamepad || !gamepad.isConnected) {
  59289. continue;
  59290. }
  59291. gamepad.update();
  59292. }
  59293. if (this._isMonitoring && !this._scene) {
  59294. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59295. }
  59296. };
  59297. // This function is called only on Chrome, which does not properly support
  59298. // connection/disconnection events and forces you to recopy again the gamepad object
  59299. GamepadManager.prototype._updateGamepadObjects = function () {
  59300. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59301. for (var i = 0; i < gamepads.length; i++) {
  59302. if (gamepads[i]) {
  59303. if (!this._babylonGamepads[gamepads[i].index]) {
  59304. var newGamepad = this._addNewGamepad(gamepads[i]);
  59305. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59306. }
  59307. else {
  59308. // Forced to copy again this object for Chrome for unknown reason
  59309. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59310. if (!this._babylonGamepads[i].isConnected) {
  59311. this._babylonGamepads[i]._isConnected = true;
  59312. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59313. }
  59314. }
  59315. }
  59316. }
  59317. };
  59318. return GamepadManager;
  59319. }());
  59320. BABYLON.GamepadManager = GamepadManager;
  59321. })(BABYLON || (BABYLON = {}));
  59322. //# sourceMappingURL=babylon.gamepadManager.js.map
  59323. var BABYLON;
  59324. (function (BABYLON) {
  59325. var StickValues = /** @class */ (function () {
  59326. function StickValues(x, y) {
  59327. this.x = x;
  59328. this.y = y;
  59329. }
  59330. return StickValues;
  59331. }());
  59332. BABYLON.StickValues = StickValues;
  59333. var Gamepad = /** @class */ (function () {
  59334. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59335. if (leftStickX === void 0) { leftStickX = 0; }
  59336. if (leftStickY === void 0) { leftStickY = 1; }
  59337. if (rightStickX === void 0) { rightStickX = 2; }
  59338. if (rightStickY === void 0) { rightStickY = 3; }
  59339. this.id = id;
  59340. this.index = index;
  59341. this.browserGamepad = browserGamepad;
  59342. this._isConnected = true;
  59343. this._invertLeftStickY = false;
  59344. this.type = Gamepad.GAMEPAD;
  59345. this._leftStickAxisX = leftStickX;
  59346. this._leftStickAxisY = leftStickY;
  59347. this._rightStickAxisX = rightStickX;
  59348. this._rightStickAxisY = rightStickY;
  59349. if (this.browserGamepad.axes.length >= 2) {
  59350. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59351. }
  59352. if (this.browserGamepad.axes.length >= 4) {
  59353. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59354. }
  59355. }
  59356. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59357. get: function () {
  59358. return this._isConnected;
  59359. },
  59360. enumerable: true,
  59361. configurable: true
  59362. });
  59363. Gamepad.prototype.onleftstickchanged = function (callback) {
  59364. this._onleftstickchanged = callback;
  59365. };
  59366. Gamepad.prototype.onrightstickchanged = function (callback) {
  59367. this._onrightstickchanged = callback;
  59368. };
  59369. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59370. get: function () {
  59371. return this._leftStick;
  59372. },
  59373. set: function (newValues) {
  59374. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59375. this._onleftstickchanged(newValues);
  59376. }
  59377. this._leftStick = newValues;
  59378. },
  59379. enumerable: true,
  59380. configurable: true
  59381. });
  59382. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59383. get: function () {
  59384. return this._rightStick;
  59385. },
  59386. set: function (newValues) {
  59387. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59388. this._onrightstickchanged(newValues);
  59389. }
  59390. this._rightStick = newValues;
  59391. },
  59392. enumerable: true,
  59393. configurable: true
  59394. });
  59395. Gamepad.prototype.update = function () {
  59396. if (this._leftStick) {
  59397. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59398. if (this._invertLeftStickY) {
  59399. this.leftStick.y *= -1;
  59400. }
  59401. }
  59402. if (this._rightStick) {
  59403. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59404. }
  59405. };
  59406. Gamepad.prototype.dispose = function () {
  59407. };
  59408. Gamepad.GAMEPAD = 0;
  59409. Gamepad.GENERIC = 1;
  59410. Gamepad.XBOX = 2;
  59411. Gamepad.POSE_ENABLED = 3;
  59412. return Gamepad;
  59413. }());
  59414. BABYLON.Gamepad = Gamepad;
  59415. var GenericPad = /** @class */ (function (_super) {
  59416. __extends(GenericPad, _super);
  59417. function GenericPad(id, index, browserGamepad) {
  59418. var _this = _super.call(this, id, index, browserGamepad) || this;
  59419. _this.onButtonDownObservable = new BABYLON.Observable();
  59420. _this.onButtonUpObservable = new BABYLON.Observable();
  59421. _this.type = Gamepad.GENERIC;
  59422. _this._buttons = new Array(browserGamepad.buttons.length);
  59423. return _this;
  59424. }
  59425. GenericPad.prototype.onbuttondown = function (callback) {
  59426. this._onbuttondown = callback;
  59427. };
  59428. GenericPad.prototype.onbuttonup = function (callback) {
  59429. this._onbuttonup = callback;
  59430. };
  59431. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59432. if (newValue !== currentValue) {
  59433. if (newValue === 1) {
  59434. if (this._onbuttondown) {
  59435. this._onbuttondown(buttonIndex);
  59436. }
  59437. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59438. }
  59439. if (newValue === 0) {
  59440. if (this._onbuttonup) {
  59441. this._onbuttonup(buttonIndex);
  59442. }
  59443. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59444. }
  59445. }
  59446. return newValue;
  59447. };
  59448. GenericPad.prototype.update = function () {
  59449. _super.prototype.update.call(this);
  59450. for (var index = 0; index < this._buttons.length; index++) {
  59451. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59452. }
  59453. };
  59454. GenericPad.prototype.dispose = function () {
  59455. _super.prototype.dispose.call(this);
  59456. this.onButtonDownObservable.clear();
  59457. this.onButtonUpObservable.clear();
  59458. };
  59459. return GenericPad;
  59460. }(Gamepad));
  59461. BABYLON.GenericPad = GenericPad;
  59462. })(BABYLON || (BABYLON = {}));
  59463. //# sourceMappingURL=babylon.gamepad.js.map
  59464. var BABYLON;
  59465. (function (BABYLON) {
  59466. var Xbox360Button;
  59467. (function (Xbox360Button) {
  59468. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  59469. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  59470. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  59471. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  59472. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  59473. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  59474. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  59475. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  59476. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  59477. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  59478. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  59479. var Xbox360Dpad;
  59480. (function (Xbox360Dpad) {
  59481. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  59482. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  59483. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  59484. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  59485. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  59486. var Xbox360Pad = /** @class */ (function (_super) {
  59487. __extends(Xbox360Pad, _super);
  59488. function Xbox360Pad(id, index, gamepad, xboxOne) {
  59489. if (xboxOne === void 0) { xboxOne = false; }
  59490. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  59491. _this._leftTrigger = 0;
  59492. _this._rightTrigger = 0;
  59493. _this.onButtonDownObservable = new BABYLON.Observable();
  59494. _this.onButtonUpObservable = new BABYLON.Observable();
  59495. _this.onPadDownObservable = new BABYLON.Observable();
  59496. _this.onPadUpObservable = new BABYLON.Observable();
  59497. _this._buttonA = 0;
  59498. _this._buttonB = 0;
  59499. _this._buttonX = 0;
  59500. _this._buttonY = 0;
  59501. _this._buttonBack = 0;
  59502. _this._buttonStart = 0;
  59503. _this._buttonLB = 0;
  59504. _this._buttonRB = 0;
  59505. _this._buttonLeftStick = 0;
  59506. _this._buttonRightStick = 0;
  59507. _this._dPadUp = 0;
  59508. _this._dPadDown = 0;
  59509. _this._dPadLeft = 0;
  59510. _this._dPadRight = 0;
  59511. _this._isXboxOnePad = false;
  59512. _this.type = BABYLON.Gamepad.XBOX;
  59513. _this._isXboxOnePad = xboxOne;
  59514. return _this;
  59515. }
  59516. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  59517. this._onlefttriggerchanged = callback;
  59518. };
  59519. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  59520. this._onrighttriggerchanged = callback;
  59521. };
  59522. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  59523. get: function () {
  59524. return this._leftTrigger;
  59525. },
  59526. set: function (newValue) {
  59527. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  59528. this._onlefttriggerchanged(newValue);
  59529. }
  59530. this._leftTrigger = newValue;
  59531. },
  59532. enumerable: true,
  59533. configurable: true
  59534. });
  59535. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  59536. get: function () {
  59537. return this._rightTrigger;
  59538. },
  59539. set: function (newValue) {
  59540. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  59541. this._onrighttriggerchanged(newValue);
  59542. }
  59543. this._rightTrigger = newValue;
  59544. },
  59545. enumerable: true,
  59546. configurable: true
  59547. });
  59548. Xbox360Pad.prototype.onbuttondown = function (callback) {
  59549. this._onbuttondown = callback;
  59550. };
  59551. Xbox360Pad.prototype.onbuttonup = function (callback) {
  59552. this._onbuttonup = callback;
  59553. };
  59554. Xbox360Pad.prototype.ondpaddown = function (callback) {
  59555. this._ondpaddown = callback;
  59556. };
  59557. Xbox360Pad.prototype.ondpadup = function (callback) {
  59558. this._ondpadup = callback;
  59559. };
  59560. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  59561. if (newValue !== currentValue) {
  59562. if (newValue === 1) {
  59563. if (this._onbuttondown) {
  59564. this._onbuttondown(buttonType);
  59565. }
  59566. this.onButtonDownObservable.notifyObservers(buttonType);
  59567. }
  59568. if (newValue === 0) {
  59569. if (this._onbuttonup) {
  59570. this._onbuttonup(buttonType);
  59571. }
  59572. this.onButtonUpObservable.notifyObservers(buttonType);
  59573. }
  59574. }
  59575. return newValue;
  59576. };
  59577. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  59578. if (newValue !== currentValue) {
  59579. if (newValue === 1) {
  59580. if (this._ondpaddown) {
  59581. this._ondpaddown(buttonType);
  59582. }
  59583. this.onPadDownObservable.notifyObservers(buttonType);
  59584. }
  59585. if (newValue === 0) {
  59586. if (this._ondpadup) {
  59587. this._ondpadup(buttonType);
  59588. }
  59589. this.onPadUpObservable.notifyObservers(buttonType);
  59590. }
  59591. }
  59592. return newValue;
  59593. };
  59594. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  59595. get: function () {
  59596. return this._buttonA;
  59597. },
  59598. set: function (value) {
  59599. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  59605. get: function () {
  59606. return this._buttonB;
  59607. },
  59608. set: function (value) {
  59609. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  59610. },
  59611. enumerable: true,
  59612. configurable: true
  59613. });
  59614. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  59615. get: function () {
  59616. return this._buttonX;
  59617. },
  59618. set: function (value) {
  59619. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  59620. },
  59621. enumerable: true,
  59622. configurable: true
  59623. });
  59624. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  59625. get: function () {
  59626. return this._buttonY;
  59627. },
  59628. set: function (value) {
  59629. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  59630. },
  59631. enumerable: true,
  59632. configurable: true
  59633. });
  59634. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  59635. get: function () {
  59636. return this._buttonStart;
  59637. },
  59638. set: function (value) {
  59639. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  59640. },
  59641. enumerable: true,
  59642. configurable: true
  59643. });
  59644. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  59645. get: function () {
  59646. return this._buttonBack;
  59647. },
  59648. set: function (value) {
  59649. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  59650. },
  59651. enumerable: true,
  59652. configurable: true
  59653. });
  59654. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  59655. get: function () {
  59656. return this._buttonLB;
  59657. },
  59658. set: function (value) {
  59659. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  59660. },
  59661. enumerable: true,
  59662. configurable: true
  59663. });
  59664. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  59665. get: function () {
  59666. return this._buttonRB;
  59667. },
  59668. set: function (value) {
  59669. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  59670. },
  59671. enumerable: true,
  59672. configurable: true
  59673. });
  59674. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  59675. get: function () {
  59676. return this._buttonLeftStick;
  59677. },
  59678. set: function (value) {
  59679. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  59680. },
  59681. enumerable: true,
  59682. configurable: true
  59683. });
  59684. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  59685. get: function () {
  59686. return this._buttonRightStick;
  59687. },
  59688. set: function (value) {
  59689. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  59690. },
  59691. enumerable: true,
  59692. configurable: true
  59693. });
  59694. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  59695. get: function () {
  59696. return this._dPadUp;
  59697. },
  59698. set: function (value) {
  59699. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  59700. },
  59701. enumerable: true,
  59702. configurable: true
  59703. });
  59704. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  59705. get: function () {
  59706. return this._dPadDown;
  59707. },
  59708. set: function (value) {
  59709. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  59715. get: function () {
  59716. return this._dPadLeft;
  59717. },
  59718. set: function (value) {
  59719. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  59720. },
  59721. enumerable: true,
  59722. configurable: true
  59723. });
  59724. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  59725. get: function () {
  59726. return this._dPadRight;
  59727. },
  59728. set: function (value) {
  59729. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  59730. },
  59731. enumerable: true,
  59732. configurable: true
  59733. });
  59734. Xbox360Pad.prototype.update = function () {
  59735. _super.prototype.update.call(this);
  59736. if (this._isXboxOnePad) {
  59737. this.buttonA = this.browserGamepad.buttons[0].value;
  59738. this.buttonB = this.browserGamepad.buttons[1].value;
  59739. this.buttonX = this.browserGamepad.buttons[2].value;
  59740. this.buttonY = this.browserGamepad.buttons[3].value;
  59741. this.buttonLB = this.browserGamepad.buttons[4].value;
  59742. this.buttonRB = this.browserGamepad.buttons[5].value;
  59743. this.leftTrigger = this.browserGamepad.axes[2];
  59744. this.rightTrigger = this.browserGamepad.axes[5];
  59745. this.buttonBack = this.browserGamepad.buttons[9].value;
  59746. this.buttonStart = this.browserGamepad.buttons[8].value;
  59747. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  59748. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  59749. this.dPadUp = this.browserGamepad.buttons[11].value;
  59750. this.dPadDown = this.browserGamepad.buttons[12].value;
  59751. this.dPadLeft = this.browserGamepad.buttons[13].value;
  59752. this.dPadRight = this.browserGamepad.buttons[14].value;
  59753. }
  59754. else {
  59755. this.buttonA = this.browserGamepad.buttons[0].value;
  59756. this.buttonB = this.browserGamepad.buttons[1].value;
  59757. this.buttonX = this.browserGamepad.buttons[2].value;
  59758. this.buttonY = this.browserGamepad.buttons[3].value;
  59759. this.buttonLB = this.browserGamepad.buttons[4].value;
  59760. this.buttonRB = this.browserGamepad.buttons[5].value;
  59761. this.leftTrigger = this.browserGamepad.buttons[6].value;
  59762. this.rightTrigger = this.browserGamepad.buttons[7].value;
  59763. this.buttonBack = this.browserGamepad.buttons[8].value;
  59764. this.buttonStart = this.browserGamepad.buttons[9].value;
  59765. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  59766. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  59767. this.dPadUp = this.browserGamepad.buttons[12].value;
  59768. this.dPadDown = this.browserGamepad.buttons[13].value;
  59769. this.dPadLeft = this.browserGamepad.buttons[14].value;
  59770. this.dPadRight = this.browserGamepad.buttons[15].value;
  59771. }
  59772. };
  59773. Xbox360Pad.prototype.dispose = function () {
  59774. _super.prototype.dispose.call(this);
  59775. this.onButtonDownObservable.clear();
  59776. this.onButtonUpObservable.clear();
  59777. this.onPadDownObservable.clear();
  59778. this.onPadUpObservable.clear();
  59779. };
  59780. return Xbox360Pad;
  59781. }(BABYLON.Gamepad));
  59782. BABYLON.Xbox360Pad = Xbox360Pad;
  59783. })(BABYLON || (BABYLON = {}));
  59784. //# sourceMappingURL=babylon.xboxGamepad.js.map
  59785. var BABYLON;
  59786. (function (BABYLON) {
  59787. var PoseEnabledControllerType;
  59788. (function (PoseEnabledControllerType) {
  59789. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  59790. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  59791. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  59792. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  59793. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  59794. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  59795. var PoseEnabledControllerHelper = /** @class */ (function () {
  59796. function PoseEnabledControllerHelper() {
  59797. }
  59798. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  59799. // Oculus Touch
  59800. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  59801. return new BABYLON.OculusTouchController(vrGamepad);
  59802. }
  59803. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  59804. return new BABYLON.WindowsMotionController(vrGamepad);
  59805. }
  59806. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  59807. return new BABYLON.ViveController(vrGamepad);
  59808. }
  59809. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  59810. return new BABYLON.GearVRController(vrGamepad);
  59811. }
  59812. else {
  59813. return new BABYLON.GenericController(vrGamepad);
  59814. }
  59815. };
  59816. return PoseEnabledControllerHelper;
  59817. }());
  59818. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  59819. var PoseEnabledController = /** @class */ (function (_super) {
  59820. __extends(PoseEnabledController, _super);
  59821. function PoseEnabledController(browserGamepad) {
  59822. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  59823. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  59824. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  59825. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  59826. // Represents device position and rotation in babylon space
  59827. _this.devicePosition = BABYLON.Vector3.Zero();
  59828. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  59829. _this.deviceScaleFactor = 1;
  59830. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  59831. _this._deviceToWorld = BABYLON.Matrix.Identity();
  59832. _this._workingMatrix = BABYLON.Matrix.Identity();
  59833. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  59834. _this.controllerType = PoseEnabledControllerType.GENERIC;
  59835. _this.position = BABYLON.Vector3.Zero();
  59836. _this.rotationQuaternion = new BABYLON.Quaternion();
  59837. _this._calculatedPosition = BABYLON.Vector3.Zero();
  59838. _this._calculatedRotation = new BABYLON.Quaternion();
  59839. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  59840. return _this;
  59841. }
  59842. PoseEnabledController.prototype.update = function () {
  59843. _super.prototype.update.call(this);
  59844. var pose = this.browserGamepad.pose;
  59845. this.updateFromDevice(pose);
  59846. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  59847. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  59848. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  59849. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  59850. if (this._mesh) {
  59851. this._mesh.position.copyFrom(this.devicePosition);
  59852. if (this._mesh.rotationQuaternion) {
  59853. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  59854. }
  59855. }
  59856. };
  59857. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  59858. if (poseData) {
  59859. this.rawPose = poseData;
  59860. if (poseData.position) {
  59861. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  59862. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  59863. this._deviceRoomPosition.z *= -1;
  59864. }
  59865. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  59866. this._calculatedPosition.addInPlace(this.position);
  59867. }
  59868. var pose = this.rawPose;
  59869. if (poseData.orientation && pose.orientation) {
  59870. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  59871. if (this._mesh) {
  59872. if (this._mesh.getScene().useRightHandedSystem) {
  59873. this._deviceRoomRotationQuaternion.z *= -1;
  59874. this._deviceRoomRotationQuaternion.w *= -1;
  59875. }
  59876. else {
  59877. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  59878. }
  59879. }
  59880. // if the camera is set, rotate to the camera's rotation
  59881. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  59882. }
  59883. }
  59884. };
  59885. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  59886. if (this._mesh) {
  59887. this._mesh.parent = null;
  59888. }
  59889. this._mesh = mesh;
  59890. if (this._poseControlledCamera) {
  59891. this._mesh.parent = this._poseControlledCamera;
  59892. }
  59893. if (!this._mesh.rotationQuaternion) {
  59894. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  59895. }
  59896. };
  59897. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  59898. this._poseControlledCamera = camera;
  59899. if (this._mesh) {
  59900. this._mesh.parent = this._poseControlledCamera;
  59901. }
  59902. };
  59903. PoseEnabledController.prototype.dispose = function () {
  59904. if (this._mesh) {
  59905. this._mesh.dispose();
  59906. }
  59907. this._mesh = null;
  59908. _super.prototype.dispose.call(this);
  59909. };
  59910. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  59911. get: function () {
  59912. return this._mesh;
  59913. },
  59914. enumerable: true,
  59915. configurable: true
  59916. });
  59917. PoseEnabledController.prototype.getForwardRay = function (length) {
  59918. if (length === void 0) { length = 100; }
  59919. if (!this.mesh) {
  59920. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  59921. }
  59922. var m = this.mesh.getWorldMatrix();
  59923. var origin = m.getTranslation();
  59924. var forward = new BABYLON.Vector3(0, 0, -1);
  59925. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59926. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59927. return new BABYLON.Ray(origin, direction, length);
  59928. };
  59929. return PoseEnabledController;
  59930. }(BABYLON.Gamepad));
  59931. BABYLON.PoseEnabledController = PoseEnabledController;
  59932. })(BABYLON || (BABYLON = {}));
  59933. //# sourceMappingURL=babylon.poseEnabledController.js.map
  59934. var BABYLON;
  59935. (function (BABYLON) {
  59936. var WebVRController = /** @class */ (function (_super) {
  59937. __extends(WebVRController, _super);
  59938. function WebVRController(vrGamepad) {
  59939. var _this = _super.call(this, vrGamepad) || this;
  59940. // Observables
  59941. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  59942. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  59943. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  59944. _this.onPadStateChangedObservable = new BABYLON.Observable();
  59945. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  59946. _this.pad = { x: 0, y: 0 };
  59947. // avoid GC, store state in a tmp object
  59948. _this._changes = {
  59949. pressChanged: false,
  59950. touchChanged: false,
  59951. valueChanged: false,
  59952. changed: false
  59953. };
  59954. _this._buttons = new Array(vrGamepad.buttons.length);
  59955. _this.hand = vrGamepad.hand;
  59956. return _this;
  59957. }
  59958. WebVRController.prototype.onButtonStateChange = function (callback) {
  59959. this._onButtonStateChange = callback;
  59960. };
  59961. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  59962. get: function () {
  59963. return this._defaultModel;
  59964. },
  59965. enumerable: true,
  59966. configurable: true
  59967. });
  59968. WebVRController.prototype.update = function () {
  59969. _super.prototype.update.call(this);
  59970. for (var index = 0; index < this._buttons.length; index++) {
  59971. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  59972. }
  59973. ;
  59974. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  59975. this.pad.x = this.leftStick.x;
  59976. this.pad.y = this.leftStick.y;
  59977. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  59978. }
  59979. };
  59980. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  59981. if (!newState) {
  59982. newState = {
  59983. pressed: false,
  59984. touched: false,
  59985. value: 0
  59986. };
  59987. }
  59988. if (!currentState) {
  59989. this._buttons[buttonIndex] = {
  59990. pressed: newState.pressed,
  59991. touched: newState.touched,
  59992. value: newState.value
  59993. };
  59994. return;
  59995. }
  59996. this._checkChanges(newState, currentState);
  59997. if (this._changes.changed) {
  59998. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  59999. this.handleButtonChange(buttonIndex, newState, this._changes);
  60000. }
  60001. this._buttons[buttonIndex].pressed = newState.pressed;
  60002. this._buttons[buttonIndex].touched = newState.touched;
  60003. // oculus triggers are never 0, thou not touched.
  60004. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60005. };
  60006. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60007. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60008. this._changes.touchChanged = newState.touched !== currentState.touched;
  60009. this._changes.valueChanged = newState.value !== currentState.value;
  60010. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60011. return this._changes;
  60012. };
  60013. WebVRController.prototype.dispose = function () {
  60014. _super.prototype.dispose.call(this);
  60015. this.onTriggerStateChangedObservable.clear();
  60016. this.onMainButtonStateChangedObservable.clear();
  60017. this.onSecondaryButtonStateChangedObservable.clear();
  60018. this.onPadStateChangedObservable.clear();
  60019. this.onPadValuesChangedObservable.clear();
  60020. };
  60021. return WebVRController;
  60022. }(BABYLON.PoseEnabledController));
  60023. BABYLON.WebVRController = WebVRController;
  60024. })(BABYLON || (BABYLON = {}));
  60025. //# sourceMappingURL=babylon.webVRController.js.map
  60026. var BABYLON;
  60027. (function (BABYLON) {
  60028. var OculusTouchController = /** @class */ (function (_super) {
  60029. __extends(OculusTouchController, _super);
  60030. function OculusTouchController(vrGamepad) {
  60031. var _this = _super.call(this, vrGamepad) || this;
  60032. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60033. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60034. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60035. return _this;
  60036. }
  60037. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60038. var _this = this;
  60039. var meshName;
  60040. // Hand
  60041. if (this.hand === 'left') {
  60042. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60043. }
  60044. else {
  60045. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60046. }
  60047. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60048. /*
  60049. Parent Mesh name: oculus_touch_left
  60050. - body
  60051. - trigger
  60052. - thumbstick
  60053. - grip
  60054. - button_y
  60055. - button_x
  60056. - button_enter
  60057. */
  60058. _this._defaultModel = newMeshes[1];
  60059. _this.attachToMesh(_this._defaultModel);
  60060. if (meshLoaded) {
  60061. meshLoaded(_this._defaultModel);
  60062. }
  60063. });
  60064. };
  60065. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60066. // helper getters for left and right hand.
  60067. get: function () {
  60068. if (this.hand === 'right') {
  60069. return this.onMainButtonStateChangedObservable;
  60070. }
  60071. else {
  60072. throw new Error('No A button on left hand');
  60073. }
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60079. get: function () {
  60080. if (this.hand === 'right') {
  60081. return this.onSecondaryButtonStateChangedObservable;
  60082. }
  60083. else {
  60084. throw new Error('No B button on left hand');
  60085. }
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60091. get: function () {
  60092. if (this.hand === 'left') {
  60093. return this.onMainButtonStateChangedObservable;
  60094. }
  60095. else {
  60096. throw new Error('No X button on right hand');
  60097. }
  60098. },
  60099. enumerable: true,
  60100. configurable: true
  60101. });
  60102. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60103. get: function () {
  60104. if (this.hand === 'left') {
  60105. return this.onSecondaryButtonStateChangedObservable;
  60106. }
  60107. else {
  60108. throw new Error('No Y button on right hand');
  60109. }
  60110. },
  60111. enumerable: true,
  60112. configurable: true
  60113. });
  60114. /*
  60115. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60116. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60117. 2) secondary trigger (same)
  60118. 3) A (right) X (left), touch, pressed = value
  60119. 4) B / Y
  60120. 5) thumb rest
  60121. */
  60122. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60123. var notifyObject = state; //{ state: state, changes: changes };
  60124. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60125. switch (buttonIdx) {
  60126. case 0:
  60127. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60128. return;
  60129. case 1:// index trigger
  60130. if (this._defaultModel) {
  60131. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60132. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60133. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60134. }
  60135. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60136. return;
  60137. case 2:// secondary trigger
  60138. if (this._defaultModel) {
  60139. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60140. }
  60141. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60142. return;
  60143. case 3:
  60144. if (this._defaultModel) {
  60145. if (notifyObject.pressed) {
  60146. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60147. }
  60148. else {
  60149. (this._defaultModel.getChildren()[1]).position.y = 0;
  60150. }
  60151. }
  60152. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60153. return;
  60154. case 4:
  60155. if (this._defaultModel) {
  60156. if (notifyObject.pressed) {
  60157. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60158. }
  60159. else {
  60160. (this._defaultModel.getChildren()[2]).position.y = 0;
  60161. }
  60162. }
  60163. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60164. return;
  60165. case 5:
  60166. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60167. return;
  60168. }
  60169. };
  60170. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60171. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60172. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60173. return OculusTouchController;
  60174. }(BABYLON.WebVRController));
  60175. BABYLON.OculusTouchController = OculusTouchController;
  60176. })(BABYLON || (BABYLON = {}));
  60177. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60178. var BABYLON;
  60179. (function (BABYLON) {
  60180. var ViveController = /** @class */ (function (_super) {
  60181. __extends(ViveController, _super);
  60182. function ViveController(vrGamepad) {
  60183. var _this = _super.call(this, vrGamepad) || this;
  60184. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60185. _this._invertLeftStickY = true;
  60186. return _this;
  60187. }
  60188. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60189. var _this = this;
  60190. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60191. /*
  60192. Parent Mesh name: ViveWand
  60193. - body
  60194. - r_gripper
  60195. - l_gripper
  60196. - menu_button
  60197. - system_button
  60198. - trackpad
  60199. - trigger
  60200. - LED
  60201. */
  60202. _this._defaultModel = newMeshes[1];
  60203. _this.attachToMesh(_this._defaultModel);
  60204. if (meshLoaded) {
  60205. meshLoaded(_this._defaultModel);
  60206. }
  60207. });
  60208. };
  60209. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60210. get: function () {
  60211. return this.onMainButtonStateChangedObservable;
  60212. },
  60213. enumerable: true,
  60214. configurable: true
  60215. });
  60216. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60217. get: function () {
  60218. return this.onMainButtonStateChangedObservable;
  60219. },
  60220. enumerable: true,
  60221. configurable: true
  60222. });
  60223. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60224. get: function () {
  60225. return this.onSecondaryButtonStateChangedObservable;
  60226. },
  60227. enumerable: true,
  60228. configurable: true
  60229. });
  60230. /**
  60231. * Vive mapping:
  60232. * 0: touchpad
  60233. * 1: trigger
  60234. * 2: left AND right buttons
  60235. * 3: menu button
  60236. */
  60237. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60238. var notifyObject = state; //{ state: state, changes: changes };
  60239. switch (buttonIdx) {
  60240. case 0:
  60241. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60242. return;
  60243. case 1:// index trigger
  60244. if (this._defaultModel) {
  60245. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60246. }
  60247. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60248. return;
  60249. case 2:// left AND right button
  60250. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60251. return;
  60252. case 3:
  60253. if (this._defaultModel) {
  60254. if (notifyObject.pressed) {
  60255. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60256. }
  60257. else {
  60258. (this._defaultModel.getChildren()[2]).position.y = 0;
  60259. }
  60260. }
  60261. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60262. return;
  60263. }
  60264. };
  60265. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60266. ViveController.MODEL_FILENAME = 'wand.babylon';
  60267. return ViveController;
  60268. }(BABYLON.WebVRController));
  60269. BABYLON.ViveController = ViveController;
  60270. })(BABYLON || (BABYLON = {}));
  60271. //# sourceMappingURL=babylon.viveController.js.map
  60272. var BABYLON;
  60273. (function (BABYLON) {
  60274. var GenericController = /** @class */ (function (_super) {
  60275. __extends(GenericController, _super);
  60276. function GenericController(vrGamepad) {
  60277. return _super.call(this, vrGamepad) || this;
  60278. }
  60279. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60280. var _this = this;
  60281. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60282. _this._defaultModel = newMeshes[1];
  60283. _this.attachToMesh(_this._defaultModel);
  60284. if (meshLoaded) {
  60285. meshLoaded(_this._defaultModel);
  60286. }
  60287. });
  60288. };
  60289. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60290. console.log("Button id: " + buttonIdx + "state: ");
  60291. console.dir(state);
  60292. };
  60293. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60294. GenericController.MODEL_FILENAME = 'generic.babylon';
  60295. return GenericController;
  60296. }(BABYLON.WebVRController));
  60297. BABYLON.GenericController = GenericController;
  60298. })(BABYLON || (BABYLON = {}));
  60299. //# sourceMappingURL=babylon.genericController.js.map
  60300. var BABYLON;
  60301. (function (BABYLON) {
  60302. var LoadedMeshInfo = /** @class */ (function () {
  60303. function LoadedMeshInfo() {
  60304. this.buttonMeshes = {};
  60305. this.axisMeshes = {};
  60306. }
  60307. return LoadedMeshInfo;
  60308. }());
  60309. var WindowsMotionController = /** @class */ (function (_super) {
  60310. __extends(WindowsMotionController, _super);
  60311. function WindowsMotionController(vrGamepad) {
  60312. var _this = _super.call(this, vrGamepad) || this;
  60313. _this._mapping = {
  60314. // Semantic button names
  60315. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60316. // A mapping of the button name to glTF model node name
  60317. // that should be transformed by button value.
  60318. buttonMeshNames: {
  60319. 'trigger': 'SELECT',
  60320. 'menu': 'MENU',
  60321. 'grip': 'GRASP',
  60322. 'thumbstick': 'THUMBSTICK_PRESS',
  60323. 'trackpad': 'TOUCHPAD_PRESS'
  60324. },
  60325. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60326. buttonObservableNames: {
  60327. 'trigger': 'onTriggerStateChangedObservable',
  60328. 'menu': 'onSecondaryButtonStateChangedObservable',
  60329. 'grip': 'onMainButtonStateChangedObservable',
  60330. 'thumbstick': 'onPadStateChangedObservable',
  60331. 'trackpad': 'onTrackpadChangedObservable'
  60332. },
  60333. // A mapping of the axis name to glTF model node name
  60334. // that should be transformed by axis value.
  60335. // This array mirrors the browserGamepad.axes array, such that
  60336. // the mesh corresponding to axis 0 is in this array index 0.
  60337. axisMeshNames: [
  60338. 'THUMBSTICK_X',
  60339. 'THUMBSTICK_Y',
  60340. 'TOUCHPAD_TOUCH_X',
  60341. 'TOUCHPAD_TOUCH_Y'
  60342. ],
  60343. pointingPoseMeshName: 'POINTING_POSE'
  60344. };
  60345. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60346. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60347. _this.trackpad = { x: 0, y: 0 };
  60348. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60349. _this._loadedMeshInfo = null;
  60350. return _this;
  60351. }
  60352. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60353. get: function () {
  60354. return this.onTriggerStateChangedObservable;
  60355. },
  60356. enumerable: true,
  60357. configurable: true
  60358. });
  60359. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60360. get: function () {
  60361. return this.onSecondaryButtonStateChangedObservable;
  60362. },
  60363. enumerable: true,
  60364. configurable: true
  60365. });
  60366. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60367. get: function () {
  60368. return this.onMainButtonStateChangedObservable;
  60369. },
  60370. enumerable: true,
  60371. configurable: true
  60372. });
  60373. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60374. get: function () {
  60375. return this.onPadStateChangedObservable;
  60376. },
  60377. enumerable: true,
  60378. configurable: true
  60379. });
  60380. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60381. get: function () {
  60382. return this.onTrackpadChangedObservable;
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60388. get: function () {
  60389. return this.onTrackpadValuesChangedObservable;
  60390. },
  60391. enumerable: true,
  60392. configurable: true
  60393. });
  60394. /**
  60395. * Called once per frame by the engine.
  60396. */
  60397. WindowsMotionController.prototype.update = function () {
  60398. _super.prototype.update.call(this);
  60399. // Only need to animate axes if there is a loaded mesh
  60400. if (this._loadedMeshInfo) {
  60401. if (this.browserGamepad.axes) {
  60402. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60403. this.trackpad.x = this.browserGamepad["axes"][2];
  60404. this.trackpad.y = this.browserGamepad["axes"][3];
  60405. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60406. }
  60407. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60408. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60409. }
  60410. }
  60411. }
  60412. };
  60413. /**
  60414. * Called once for each button that changed state since the last frame
  60415. * @param buttonIdx Which button index changed
  60416. * @param state New state of the button
  60417. * @param changes Which properties on the state changed since last frame
  60418. */
  60419. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60420. var buttonName = this._mapping.buttons[buttonIdx];
  60421. if (!buttonName) {
  60422. return;
  60423. }
  60424. // Only emit events for buttons that we know how to map from index to name
  60425. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60426. if (observable) {
  60427. observable.notifyObservers(state);
  60428. }
  60429. this.lerpButtonTransform(buttonName, state.value);
  60430. };
  60431. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60432. // If there is no loaded mesh, there is nothing to transform.
  60433. if (!this._loadedMeshInfo) {
  60434. return;
  60435. }
  60436. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60437. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60438. return;
  60439. }
  60440. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60441. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60442. };
  60443. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60444. if (!this._loadedMeshInfo) {
  60445. return;
  60446. }
  60447. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60448. if (!meshInfo) {
  60449. return;
  60450. }
  60451. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60452. return;
  60453. }
  60454. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60455. var lerpValue = axisValue * 0.5 + 0.5;
  60456. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60457. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60458. };
  60459. /**
  60460. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60461. * @param scene scene in which to add meshes
  60462. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60463. */
  60464. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60465. var _this = this;
  60466. if (forceDefault === void 0) { forceDefault = false; }
  60467. var path;
  60468. var filename;
  60469. // Checking if GLB loader is present
  60470. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  60471. // Determine the device specific folder based on the ID suffix
  60472. var device = 'default';
  60473. if (this.id && !forceDefault) {
  60474. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  60475. device = ((match && match[0]) || device);
  60476. }
  60477. // Hand
  60478. if (this.hand === 'left') {
  60479. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  60480. }
  60481. else {
  60482. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  60483. }
  60484. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  60485. }
  60486. else {
  60487. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  60488. path = BABYLON.GenericController.MODEL_BASE_URL;
  60489. filename = BABYLON.GenericController.MODEL_FILENAME;
  60490. }
  60491. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  60492. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  60493. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  60494. if (!_this._loadedMeshInfo) {
  60495. return;
  60496. }
  60497. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  60498. _this.attachToMesh(_this._defaultModel);
  60499. if (meshLoaded) {
  60500. meshLoaded(_this._defaultModel);
  60501. }
  60502. }, null, function (scene, message) {
  60503. BABYLON.Tools.Log(message);
  60504. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  60505. if (!forceDefault) {
  60506. _this.initControllerMesh(scene, meshLoaded, true);
  60507. }
  60508. });
  60509. };
  60510. /**
  60511. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  60512. * can be transformed by button presses and axes values, based on this._mapping.
  60513. *
  60514. * @param scene scene in which the meshes exist
  60515. * @param meshes list of meshes that make up the controller model to process
  60516. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  60517. */
  60518. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  60519. var loadedMeshInfo = null;
  60520. // Create a new mesh to contain the glTF hierarchy
  60521. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  60522. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  60523. var childMesh = null;
  60524. for (var i = 0; i < meshes.length; i++) {
  60525. var mesh = meshes[i];
  60526. if (!mesh.parent) {
  60527. // Exclude controller meshes from picking results
  60528. mesh.isPickable = false;
  60529. // Handle root node, attach to the new parentMesh
  60530. childMesh = mesh;
  60531. break;
  60532. }
  60533. }
  60534. if (childMesh) {
  60535. childMesh.setParent(parentMesh);
  60536. // Create our mesh info. Note that this method will always return non-null.
  60537. loadedMeshInfo = this.createMeshInfo(parentMesh);
  60538. }
  60539. else {
  60540. BABYLON.Tools.Warn('Could not find root node in model file.');
  60541. }
  60542. return loadedMeshInfo;
  60543. };
  60544. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  60545. var loadedMeshInfo = new LoadedMeshInfo();
  60546. var i;
  60547. loadedMeshInfo.rootNode = rootNode;
  60548. // Reset the caches
  60549. loadedMeshInfo.buttonMeshes = {};
  60550. loadedMeshInfo.axisMeshes = {};
  60551. // Button Meshes
  60552. for (i = 0; i < this._mapping.buttons.length; i++) {
  60553. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  60554. if (!buttonMeshName) {
  60555. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  60556. continue;
  60557. }
  60558. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  60559. if (!buttonMesh) {
  60560. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  60561. continue;
  60562. }
  60563. var buttonMeshInfo = {
  60564. index: i,
  60565. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  60566. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  60567. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  60568. };
  60569. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  60570. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  60571. }
  60572. else {
  60573. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  60574. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  60575. '(VALUE: ' + !!buttonMeshInfo.value +
  60576. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  60577. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  60578. ')');
  60579. }
  60580. }
  60581. // Axis Meshes
  60582. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  60583. var axisMeshName = this._mapping.axisMeshNames[i];
  60584. if (!axisMeshName) {
  60585. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  60586. continue;
  60587. }
  60588. var axisMesh = getChildByName(rootNode, axisMeshName);
  60589. if (!axisMesh) {
  60590. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  60591. continue;
  60592. }
  60593. var axisMeshInfo = {
  60594. index: i,
  60595. value: getImmediateChildByName(axisMesh, 'VALUE'),
  60596. min: getImmediateChildByName(axisMesh, 'MIN'),
  60597. max: getImmediateChildByName(axisMesh, 'MAX')
  60598. };
  60599. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  60600. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  60601. }
  60602. else {
  60603. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  60604. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  60605. '(VALUE: ' + !!axisMeshInfo.value +
  60606. ', MIN: ' + !!axisMeshInfo.min +
  60607. ', MAX:' + !!axisMeshInfo.max +
  60608. ')');
  60609. }
  60610. }
  60611. // Pointing Ray
  60612. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  60613. if (!loadedMeshInfo.pointingPoseNode) {
  60614. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  60615. }
  60616. return loadedMeshInfo;
  60617. // Look through all children recursively. This will return null if no mesh exists with the given name.
  60618. function getChildByName(node, name) {
  60619. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  60620. }
  60621. // Look through only immediate children. This will return null if no mesh exists with the given name.
  60622. function getImmediateChildByName(node, name) {
  60623. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  60624. }
  60625. };
  60626. WindowsMotionController.prototype.getForwardRay = function (length) {
  60627. if (length === void 0) { length = 100; }
  60628. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  60629. return _super.prototype.getForwardRay.call(this, length);
  60630. }
  60631. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  60632. var origin = m.getTranslation();
  60633. var forward = new BABYLON.Vector3(0, 0, -1);
  60634. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60635. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60636. return new BABYLON.Ray(origin, direction, length);
  60637. };
  60638. WindowsMotionController.prototype.dispose = function () {
  60639. _super.prototype.dispose.call(this);
  60640. this.onTrackpadChangedObservable.clear();
  60641. };
  60642. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  60643. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  60644. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  60645. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  60646. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  60647. return WindowsMotionController;
  60648. }(BABYLON.WebVRController));
  60649. BABYLON.WindowsMotionController = WindowsMotionController;
  60650. })(BABYLON || (BABYLON = {}));
  60651. //# sourceMappingURL=babylon.windowsMotionController.js.map
  60652. var BABYLON;
  60653. (function (BABYLON) {
  60654. var GearVRController = /** @class */ (function (_super) {
  60655. __extends(GearVRController, _super);
  60656. function GearVRController(vrGamepad) {
  60657. var _this = _super.call(this, vrGamepad) || this;
  60658. _this._buttonIndexToObservableNameMap = [
  60659. 'onTrackpadChangedObservable',
  60660. 'onTriggerStateChangedObservable' // Trigger
  60661. ];
  60662. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  60663. return _this;
  60664. }
  60665. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60666. var _this = this;
  60667. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  60668. _this._defaultModel = newMeshes[1];
  60669. _this.attachToMesh(_this._defaultModel);
  60670. if (meshLoaded) {
  60671. meshLoaded(_this._defaultModel);
  60672. }
  60673. });
  60674. };
  60675. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60676. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  60677. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  60678. // Only emit events for buttons that we know how to map from index to observable
  60679. var observable = this[observableName];
  60680. if (observable) {
  60681. observable.notifyObservers(state);
  60682. }
  60683. }
  60684. };
  60685. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60686. GearVRController.MODEL_FILENAME = 'generic.babylon';
  60687. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  60688. return GearVRController;
  60689. }(BABYLON.WebVRController));
  60690. BABYLON.GearVRController = GearVRController;
  60691. })(BABYLON || (BABYLON = {}));
  60692. //# sourceMappingURL=babylon.gearVRController.js.map
  60693. var BABYLON;
  60694. (function (BABYLON) {
  60695. var FollowCamera = /** @class */ (function (_super) {
  60696. __extends(FollowCamera, _super);
  60697. function FollowCamera(name, position, scene, lockedTarget) {
  60698. if (lockedTarget === void 0) { lockedTarget = null; }
  60699. var _this = _super.call(this, name, position, scene) || this;
  60700. _this.radius = 12;
  60701. _this.rotationOffset = 0;
  60702. _this.heightOffset = 4;
  60703. _this.cameraAcceleration = 0.05;
  60704. _this.maxCameraSpeed = 20;
  60705. _this.lockedTarget = lockedTarget;
  60706. return _this;
  60707. }
  60708. FollowCamera.prototype.getRadians = function (degrees) {
  60709. return degrees * Math.PI / 180;
  60710. };
  60711. FollowCamera.prototype.follow = function (cameraTarget) {
  60712. if (!cameraTarget)
  60713. return;
  60714. var yRotation;
  60715. if (cameraTarget.rotationQuaternion) {
  60716. var rotMatrix = new BABYLON.Matrix();
  60717. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  60718. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  60719. }
  60720. else {
  60721. yRotation = cameraTarget.rotation.y;
  60722. }
  60723. var radians = this.getRadians(this.rotationOffset) + yRotation;
  60724. var targetPosition = cameraTarget.getAbsolutePosition();
  60725. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  60726. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  60727. var dx = targetX - this.position.x;
  60728. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  60729. var dz = (targetZ) - this.position.z;
  60730. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  60731. var vy = dy * this.cameraAcceleration;
  60732. var vz = dz * this.cameraAcceleration * 2;
  60733. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  60734. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60735. }
  60736. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  60737. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60738. }
  60739. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  60740. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60741. }
  60742. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  60743. this.setTarget(targetPosition);
  60744. };
  60745. FollowCamera.prototype._checkInputs = function () {
  60746. _super.prototype._checkInputs.call(this);
  60747. if (this.lockedTarget) {
  60748. this.follow(this.lockedTarget);
  60749. }
  60750. };
  60751. FollowCamera.prototype.getClassName = function () {
  60752. return "FollowCamera";
  60753. };
  60754. __decorate([
  60755. BABYLON.serialize()
  60756. ], FollowCamera.prototype, "radius", void 0);
  60757. __decorate([
  60758. BABYLON.serialize()
  60759. ], FollowCamera.prototype, "rotationOffset", void 0);
  60760. __decorate([
  60761. BABYLON.serialize()
  60762. ], FollowCamera.prototype, "heightOffset", void 0);
  60763. __decorate([
  60764. BABYLON.serialize()
  60765. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  60766. __decorate([
  60767. BABYLON.serialize()
  60768. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  60769. __decorate([
  60770. BABYLON.serializeAsMeshReference("lockedTargetId")
  60771. ], FollowCamera.prototype, "lockedTarget", void 0);
  60772. return FollowCamera;
  60773. }(BABYLON.TargetCamera));
  60774. BABYLON.FollowCamera = FollowCamera;
  60775. var ArcFollowCamera = /** @class */ (function (_super) {
  60776. __extends(ArcFollowCamera, _super);
  60777. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  60778. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  60779. _this.alpha = alpha;
  60780. _this.beta = beta;
  60781. _this.radius = radius;
  60782. _this.target = target;
  60783. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  60784. _this.follow();
  60785. return _this;
  60786. }
  60787. ArcFollowCamera.prototype.follow = function () {
  60788. if (!this.target) {
  60789. return;
  60790. }
  60791. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  60792. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  60793. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  60794. var targetPosition = this.target.getAbsolutePosition();
  60795. this.position = targetPosition.add(this._cartesianCoordinates);
  60796. this.setTarget(targetPosition);
  60797. };
  60798. ArcFollowCamera.prototype._checkInputs = function () {
  60799. _super.prototype._checkInputs.call(this);
  60800. this.follow();
  60801. };
  60802. ArcFollowCamera.prototype.getClassName = function () {
  60803. return "ArcFollowCamera";
  60804. };
  60805. return ArcFollowCamera;
  60806. }(BABYLON.TargetCamera));
  60807. BABYLON.ArcFollowCamera = ArcFollowCamera;
  60808. })(BABYLON || (BABYLON = {}));
  60809. //# sourceMappingURL=babylon.followCamera.js.map
  60810. var BABYLON;
  60811. (function (BABYLON) {
  60812. // We're mainly based on the logic defined into the FreeCamera code
  60813. var UniversalCamera = /** @class */ (function (_super) {
  60814. __extends(UniversalCamera, _super);
  60815. //-- end properties for backward compatibility for inputs
  60816. function UniversalCamera(name, position, scene) {
  60817. var _this = _super.call(this, name, position, scene) || this;
  60818. _this.inputs.addGamepad();
  60819. return _this;
  60820. }
  60821. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  60822. //-- Begin properties for backward compatibility for inputs
  60823. get: function () {
  60824. var gamepad = this.inputs.attached["gamepad"];
  60825. if (gamepad)
  60826. return gamepad.gamepadAngularSensibility;
  60827. return 0;
  60828. },
  60829. set: function (value) {
  60830. var gamepad = this.inputs.attached["gamepad"];
  60831. if (gamepad)
  60832. gamepad.gamepadAngularSensibility = value;
  60833. },
  60834. enumerable: true,
  60835. configurable: true
  60836. });
  60837. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  60838. get: function () {
  60839. var gamepad = this.inputs.attached["gamepad"];
  60840. if (gamepad)
  60841. return gamepad.gamepadMoveSensibility;
  60842. return 0;
  60843. },
  60844. set: function (value) {
  60845. var gamepad = this.inputs.attached["gamepad"];
  60846. if (gamepad)
  60847. gamepad.gamepadMoveSensibility = value;
  60848. },
  60849. enumerable: true,
  60850. configurable: true
  60851. });
  60852. UniversalCamera.prototype.getClassName = function () {
  60853. return "UniversalCamera";
  60854. };
  60855. return UniversalCamera;
  60856. }(BABYLON.TouchCamera));
  60857. BABYLON.UniversalCamera = UniversalCamera;
  60858. })(BABYLON || (BABYLON = {}));
  60859. //# sourceMappingURL=babylon.universalCamera.js.map
  60860. var BABYLON;
  60861. (function (BABYLON) {
  60862. // We're mainly based on the logic defined into the FreeCamera code
  60863. var GamepadCamera = /** @class */ (function (_super) {
  60864. __extends(GamepadCamera, _super);
  60865. //-- end properties for backward compatibility for inputs
  60866. function GamepadCamera(name, position, scene) {
  60867. return _super.call(this, name, position, scene) || this;
  60868. }
  60869. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  60870. //-- Begin properties for backward compatibility for inputs
  60871. get: function () {
  60872. var gamepad = this.inputs.attached["gamepad"];
  60873. if (gamepad)
  60874. return gamepad.gamepadAngularSensibility;
  60875. return 0;
  60876. },
  60877. set: function (value) {
  60878. var gamepad = this.inputs.attached["gamepad"];
  60879. if (gamepad)
  60880. gamepad.gamepadAngularSensibility = value;
  60881. },
  60882. enumerable: true,
  60883. configurable: true
  60884. });
  60885. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  60886. get: function () {
  60887. var gamepad = this.inputs.attached["gamepad"];
  60888. if (gamepad)
  60889. return gamepad.gamepadMoveSensibility;
  60890. return 0;
  60891. },
  60892. set: function (value) {
  60893. var gamepad = this.inputs.attached["gamepad"];
  60894. if (gamepad)
  60895. gamepad.gamepadMoveSensibility = value;
  60896. },
  60897. enumerable: true,
  60898. configurable: true
  60899. });
  60900. GamepadCamera.prototype.getClassName = function () {
  60901. return "GamepadCamera";
  60902. };
  60903. return GamepadCamera;
  60904. }(BABYLON.UniversalCamera));
  60905. BABYLON.GamepadCamera = GamepadCamera;
  60906. })(BABYLON || (BABYLON = {}));
  60907. //# sourceMappingURL=babylon.gamepadCamera.js.map
  60908. var BABYLON;
  60909. (function (BABYLON) {
  60910. var PostProcessRenderPipelineManager = /** @class */ (function () {
  60911. function PostProcessRenderPipelineManager() {
  60912. this._renderPipelines = {};
  60913. }
  60914. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  60915. this._renderPipelines[renderPipeline._name] = renderPipeline;
  60916. };
  60917. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  60918. if (unique === void 0) { unique = false; }
  60919. var renderPipeline = this._renderPipelines[renderPipelineName];
  60920. if (!renderPipeline) {
  60921. return;
  60922. }
  60923. renderPipeline._attachCameras(cameras, unique);
  60924. };
  60925. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  60926. var renderPipeline = this._renderPipelines[renderPipelineName];
  60927. if (!renderPipeline) {
  60928. return;
  60929. }
  60930. renderPipeline._detachCameras(cameras);
  60931. };
  60932. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  60933. var renderPipeline = this._renderPipelines[renderPipelineName];
  60934. if (!renderPipeline) {
  60935. return;
  60936. }
  60937. renderPipeline._enableEffect(renderEffectName, cameras);
  60938. };
  60939. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  60940. var renderPipeline = this._renderPipelines[renderPipelineName];
  60941. if (!renderPipeline) {
  60942. return;
  60943. }
  60944. renderPipeline._disableEffect(renderEffectName, cameras);
  60945. };
  60946. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  60947. var renderPipeline = this._renderPipelines[renderPipelineName];
  60948. if (!renderPipeline) {
  60949. return;
  60950. }
  60951. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  60952. };
  60953. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  60954. var renderPipeline = this._renderPipelines[renderPipelineName];
  60955. if (!renderPipeline) {
  60956. return;
  60957. }
  60958. renderPipeline._disableDisplayOnlyPass(cameras);
  60959. };
  60960. PostProcessRenderPipelineManager.prototype.update = function () {
  60961. for (var renderPipelineName in this._renderPipelines) {
  60962. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60963. var pipeline = this._renderPipelines[renderPipelineName];
  60964. if (!pipeline.isSupported) {
  60965. pipeline.dispose();
  60966. delete this._renderPipelines[renderPipelineName];
  60967. }
  60968. else {
  60969. pipeline._update();
  60970. }
  60971. }
  60972. }
  60973. };
  60974. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  60975. for (var renderPipelineName in this._renderPipelines) {
  60976. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60977. var pipeline = this._renderPipelines[renderPipelineName];
  60978. pipeline._rebuild();
  60979. }
  60980. }
  60981. };
  60982. PostProcessRenderPipelineManager.prototype.dispose = function () {
  60983. for (var renderPipelineName in this._renderPipelines) {
  60984. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60985. var pipeline = this._renderPipelines[renderPipelineName];
  60986. pipeline.dispose();
  60987. }
  60988. }
  60989. };
  60990. return PostProcessRenderPipelineManager;
  60991. }());
  60992. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  60993. })(BABYLON || (BABYLON = {}));
  60994. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  60995. var BABYLON;
  60996. (function (BABYLON) {
  60997. var PostProcessRenderPass = /** @class */ (function () {
  60998. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  60999. this._refCount = 0;
  61000. this._name = name;
  61001. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61002. this.setRenderList(renderList);
  61003. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61004. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61005. this._scene = scene;
  61006. this._renderList = renderList;
  61007. }
  61008. // private
  61009. PostProcessRenderPass.prototype._incRefCount = function () {
  61010. if (this._refCount === 0) {
  61011. this._scene.customRenderTargets.push(this._renderTexture);
  61012. }
  61013. return ++this._refCount;
  61014. };
  61015. PostProcessRenderPass.prototype._decRefCount = function () {
  61016. this._refCount--;
  61017. if (this._refCount <= 0) {
  61018. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61019. }
  61020. return this._refCount;
  61021. };
  61022. PostProcessRenderPass.prototype._update = function () {
  61023. this.setRenderList(this._renderList);
  61024. };
  61025. // public
  61026. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61027. this._renderTexture.renderList = renderList;
  61028. };
  61029. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61030. return this._renderTexture;
  61031. };
  61032. return PostProcessRenderPass;
  61033. }());
  61034. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61035. })(BABYLON || (BABYLON = {}));
  61036. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61037. var BABYLON;
  61038. (function (BABYLON) {
  61039. var PostProcessRenderEffect = /** @class */ (function () {
  61040. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61041. this._name = name;
  61042. this._singleInstance = singleInstance || true;
  61043. this._getPostProcess = getPostProcess;
  61044. this._cameras = {};
  61045. this._indicesForCamera = {};
  61046. this._postProcesses = {};
  61047. this._renderPasses = {};
  61048. this._renderEffectAsPasses = {};
  61049. }
  61050. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61051. get: function () {
  61052. for (var index in this._postProcesses) {
  61053. if (!this._postProcesses[index].isSupported) {
  61054. return false;
  61055. }
  61056. }
  61057. return true;
  61058. },
  61059. enumerable: true,
  61060. configurable: true
  61061. });
  61062. PostProcessRenderEffect.prototype._update = function () {
  61063. for (var renderPassName in this._renderPasses) {
  61064. this._renderPasses[renderPassName]._update();
  61065. }
  61066. };
  61067. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61068. this._renderPasses[renderPass._name] = renderPass;
  61069. this._linkParameters();
  61070. };
  61071. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61072. delete this._renderPasses[renderPass._name];
  61073. this._linkParameters();
  61074. };
  61075. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61076. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61077. this._linkParameters();
  61078. };
  61079. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61080. for (var renderPassName in this._renderPasses) {
  61081. if (renderPassName === passName) {
  61082. return this._renderPasses[passName];
  61083. }
  61084. }
  61085. return null;
  61086. };
  61087. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61088. this._renderPasses = {};
  61089. this._linkParameters();
  61090. };
  61091. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61092. var cameraKey;
  61093. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61094. if (!cams) {
  61095. return;
  61096. }
  61097. for (var i = 0; i < cams.length; i++) {
  61098. var camera = cams[i];
  61099. var cameraName = camera.name;
  61100. if (this._singleInstance) {
  61101. cameraKey = 0;
  61102. }
  61103. else {
  61104. cameraKey = cameraName;
  61105. }
  61106. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61107. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61108. if (!this._indicesForCamera[cameraName]) {
  61109. this._indicesForCamera[cameraName] = [];
  61110. }
  61111. this._indicesForCamera[cameraName].push(index);
  61112. if (!this._cameras[cameraName]) {
  61113. this._cameras[cameraName] = camera;
  61114. }
  61115. for (var passName in this._renderPasses) {
  61116. this._renderPasses[passName]._incRefCount();
  61117. }
  61118. }
  61119. this._linkParameters();
  61120. };
  61121. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61122. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61123. if (!cams) {
  61124. return;
  61125. }
  61126. for (var i = 0; i < cams.length; i++) {
  61127. var camera = cams[i];
  61128. var cameraName = camera.name;
  61129. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61130. if (this._cameras[cameraName]) {
  61131. //this._indicesForCamera.splice(index, 1);
  61132. this._cameras[cameraName] = null;
  61133. }
  61134. for (var passName in this._renderPasses) {
  61135. this._renderPasses[passName]._decRefCount();
  61136. }
  61137. }
  61138. };
  61139. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61140. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61141. if (!cams) {
  61142. return;
  61143. }
  61144. for (var i = 0; i < cams.length; i++) {
  61145. var camera = cams[i];
  61146. var cameraName = camera.name;
  61147. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61148. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61149. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61150. }
  61151. }
  61152. for (var passName in this._renderPasses) {
  61153. this._renderPasses[passName]._incRefCount();
  61154. }
  61155. }
  61156. };
  61157. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61158. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61159. if (!cams) {
  61160. return;
  61161. }
  61162. for (var i = 0; i < cams.length; i++) {
  61163. var camera = cams[i];
  61164. var cameraName = camera.Name;
  61165. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61166. for (var passName in this._renderPasses) {
  61167. this._renderPasses[passName]._decRefCount();
  61168. }
  61169. }
  61170. };
  61171. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61172. if (this._singleInstance) {
  61173. return this._postProcesses[0];
  61174. }
  61175. else {
  61176. if (!camera) {
  61177. return null;
  61178. }
  61179. return this._postProcesses[camera.name];
  61180. }
  61181. };
  61182. PostProcessRenderEffect.prototype._linkParameters = function () {
  61183. var _this = this;
  61184. for (var index in this._postProcesses) {
  61185. if (this.applyParameters) {
  61186. this.applyParameters(this._postProcesses[index]);
  61187. }
  61188. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61189. _this._linkTextures(effect);
  61190. });
  61191. }
  61192. };
  61193. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61194. for (var renderPassName in this._renderPasses) {
  61195. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61196. }
  61197. for (var renderEffectName in this._renderEffectAsPasses) {
  61198. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61199. }
  61200. };
  61201. return PostProcessRenderEffect;
  61202. }());
  61203. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61204. })(BABYLON || (BABYLON = {}));
  61205. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61206. var BABYLON;
  61207. (function (BABYLON) {
  61208. var PostProcessRenderPipeline = /** @class */ (function () {
  61209. function PostProcessRenderPipeline(engine, name) {
  61210. this._engine = engine;
  61211. this._name = name;
  61212. this._renderEffects = {};
  61213. this._renderEffectsForIsolatedPass = new Array();
  61214. this._cameras = [];
  61215. }
  61216. PostProcessRenderPipeline.prototype.getClassName = function () {
  61217. return "PostProcessRenderPipeline";
  61218. };
  61219. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61220. get: function () {
  61221. for (var renderEffectName in this._renderEffects) {
  61222. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61223. if (!this._renderEffects[renderEffectName].isSupported) {
  61224. return false;
  61225. }
  61226. }
  61227. }
  61228. return true;
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61234. this._renderEffects[renderEffect._name] = renderEffect;
  61235. };
  61236. // private
  61237. PostProcessRenderPipeline.prototype._rebuild = function () {
  61238. };
  61239. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61240. var renderEffects = this._renderEffects[renderEffectName];
  61241. if (!renderEffects) {
  61242. return;
  61243. }
  61244. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61245. };
  61246. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61247. var renderEffects = this._renderEffects[renderEffectName];
  61248. if (!renderEffects) {
  61249. return;
  61250. }
  61251. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61252. };
  61253. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61254. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61255. if (!cams) {
  61256. return;
  61257. }
  61258. var indicesToDelete = [];
  61259. var i;
  61260. for (i = 0; i < cams.length; i++) {
  61261. var camera = cams[i];
  61262. var cameraName = camera.name;
  61263. if (this._cameras.indexOf(camera) === -1) {
  61264. this._cameras[cameraName] = camera;
  61265. }
  61266. else if (unique) {
  61267. indicesToDelete.push(i);
  61268. }
  61269. }
  61270. for (i = 0; i < indicesToDelete.length; i++) {
  61271. cameras.splice(indicesToDelete[i], 1);
  61272. }
  61273. for (var renderEffectName in this._renderEffects) {
  61274. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61275. this._renderEffects[renderEffectName]._attachCameras(cams);
  61276. }
  61277. }
  61278. };
  61279. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61280. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61281. if (!cams) {
  61282. return;
  61283. }
  61284. for (var renderEffectName in this._renderEffects) {
  61285. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61286. this._renderEffects[renderEffectName]._detachCameras(cams);
  61287. }
  61288. }
  61289. for (var i = 0; i < cams.length; i++) {
  61290. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61291. }
  61292. };
  61293. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61294. var _this = this;
  61295. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61296. if (!cams) {
  61297. return;
  61298. }
  61299. var pass = null;
  61300. var renderEffectName;
  61301. for (renderEffectName in this._renderEffects) {
  61302. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61303. pass = this._renderEffects[renderEffectName].getPass(passName);
  61304. if (pass != null) {
  61305. break;
  61306. }
  61307. }
  61308. }
  61309. if (pass === null) {
  61310. return;
  61311. }
  61312. for (renderEffectName in this._renderEffects) {
  61313. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61314. this._renderEffects[renderEffectName]._disable(cams);
  61315. }
  61316. }
  61317. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61318. for (var i = 0; i < cams.length; i++) {
  61319. var camera = cams[i];
  61320. var cameraName = camera.name;
  61321. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61322. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61323. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61324. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61325. }
  61326. };
  61327. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61328. var _this = this;
  61329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61330. if (!cams) {
  61331. return;
  61332. }
  61333. for (var i = 0; i < cams.length; i++) {
  61334. var camera = cams[i];
  61335. var cameraName = camera.name;
  61336. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61337. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61338. }
  61339. for (var renderEffectName in this._renderEffects) {
  61340. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61341. this._renderEffects[renderEffectName]._enable(cams);
  61342. }
  61343. }
  61344. };
  61345. PostProcessRenderPipeline.prototype._update = function () {
  61346. for (var renderEffectName in this._renderEffects) {
  61347. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61348. this._renderEffects[renderEffectName]._update();
  61349. }
  61350. }
  61351. for (var i = 0; i < this._cameras.length; i++) {
  61352. var cameraName = this._cameras[i].name;
  61353. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61354. this._renderEffectsForIsolatedPass[cameraName]._update();
  61355. }
  61356. }
  61357. };
  61358. PostProcessRenderPipeline.prototype._reset = function () {
  61359. this._renderEffects = {};
  61360. this._renderEffectsForIsolatedPass = new Array();
  61361. };
  61362. PostProcessRenderPipeline.prototype.dispose = function () {
  61363. // Must be implemented by children
  61364. };
  61365. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61366. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61367. __decorate([
  61368. BABYLON.serialize()
  61369. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61370. return PostProcessRenderPipeline;
  61371. }());
  61372. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61373. })(BABYLON || (BABYLON = {}));
  61374. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61375. var BABYLON;
  61376. (function (BABYLON) {
  61377. var DepthRenderer = /** @class */ (function () {
  61378. function DepthRenderer(scene, type) {
  61379. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61380. var _this = this;
  61381. this._scene = scene;
  61382. var engine = scene.getEngine();
  61383. // Render target
  61384. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61385. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61386. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61387. this._depthMap.refreshRate = 1;
  61388. this._depthMap.renderParticles = false;
  61389. this._depthMap.renderList = null;
  61390. // set default depth value to 1.0 (far away)
  61391. this._depthMap.onClearObservable.add(function (engine) {
  61392. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61393. });
  61394. // Custom render function
  61395. var renderSubMesh = function (subMesh) {
  61396. var mesh = subMesh.getRenderingMesh();
  61397. var scene = _this._scene;
  61398. var engine = scene.getEngine();
  61399. var material = subMesh.getMaterial();
  61400. if (!material) {
  61401. return;
  61402. }
  61403. // Culling and reverse (right handed system)
  61404. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61405. // Managing instances
  61406. var batch = mesh._getInstancesRenderList(subMesh._id);
  61407. if (batch.mustReturn) {
  61408. return;
  61409. }
  61410. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61411. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61412. engine.enableEffect(_this._effect);
  61413. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61414. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61415. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61416. // Alpha test
  61417. if (material && material.needAlphaTesting()) {
  61418. var alphaTexture = material.getAlphaTestTexture();
  61419. if (alphaTexture) {
  61420. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61421. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61422. }
  61423. }
  61424. // Bones
  61425. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61426. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61427. }
  61428. // Draw
  61429. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61430. }
  61431. };
  61432. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61433. var index;
  61434. if (depthOnlySubMeshes.length) {
  61435. engine.setColorWrite(false);
  61436. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61437. renderSubMesh(depthOnlySubMeshes.data[index]);
  61438. }
  61439. engine.setColorWrite(true);
  61440. }
  61441. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61442. renderSubMesh(opaqueSubMeshes.data[index]);
  61443. }
  61444. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61445. renderSubMesh(alphaTestSubMeshes.data[index]);
  61446. }
  61447. };
  61448. }
  61449. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61450. var material = subMesh.getMaterial();
  61451. if (material.disableDepthWrite) {
  61452. return false;
  61453. }
  61454. var defines = [];
  61455. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61456. var mesh = subMesh.getMesh();
  61457. // Alpha test
  61458. if (material && material.needAlphaTesting()) {
  61459. defines.push("#define ALPHATEST");
  61460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61461. attribs.push(BABYLON.VertexBuffer.UVKind);
  61462. defines.push("#define UV1");
  61463. }
  61464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61466. defines.push("#define UV2");
  61467. }
  61468. }
  61469. // Bones
  61470. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61473. if (mesh.numBoneInfluencers > 4) {
  61474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61476. }
  61477. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61478. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61479. }
  61480. else {
  61481. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61482. }
  61483. // Instances
  61484. if (useInstances) {
  61485. defines.push("#define INSTANCES");
  61486. attribs.push("world0");
  61487. attribs.push("world1");
  61488. attribs.push("world2");
  61489. attribs.push("world3");
  61490. }
  61491. // Get correct effect
  61492. var join = defines.join("\n");
  61493. if (this._cachedDefines !== join) {
  61494. this._cachedDefines = join;
  61495. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  61496. }
  61497. return this._effect.isReady();
  61498. };
  61499. DepthRenderer.prototype.getDepthMap = function () {
  61500. return this._depthMap;
  61501. };
  61502. // Methods
  61503. DepthRenderer.prototype.dispose = function () {
  61504. this._depthMap.dispose();
  61505. };
  61506. return DepthRenderer;
  61507. }());
  61508. BABYLON.DepthRenderer = DepthRenderer;
  61509. })(BABYLON || (BABYLON = {}));
  61510. //# sourceMappingURL=babylon.depthRenderer.js.map
  61511. var BABYLON;
  61512. (function (BABYLON) {
  61513. var SSAORenderingPipeline = /** @class */ (function (_super) {
  61514. __extends(SSAORenderingPipeline, _super);
  61515. /**
  61516. * @constructor
  61517. * @param {string} name - The rendering pipeline name
  61518. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61519. * @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 }
  61520. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61521. */
  61522. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  61523. var _this = _super.call(this, scene.getEngine(), name) || this;
  61524. // Members
  61525. /**
  61526. * The PassPostProcess id in the pipeline that contains the original scene color
  61527. * @type {string}
  61528. */
  61529. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61530. /**
  61531. * The SSAO PostProcess id in the pipeline
  61532. * @type {string}
  61533. */
  61534. _this.SSAORenderEffect = "SSAORenderEffect";
  61535. /**
  61536. * The horizontal blur PostProcess id in the pipeline
  61537. * @type {string}
  61538. */
  61539. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61540. /**
  61541. * The vertical blur PostProcess id in the pipeline
  61542. * @type {string}
  61543. */
  61544. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61545. /**
  61546. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61547. * @type {string}
  61548. */
  61549. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61550. /**
  61551. * The output strength of the SSAO post-process. Default value is 1.0.
  61552. * @type {number}
  61553. */
  61554. _this.totalStrength = 1.0;
  61555. /**
  61556. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  61557. * @type {number}
  61558. */
  61559. _this.radius = 0.0001;
  61560. /**
  61561. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  61562. * Must not be equal to fallOff and superior to fallOff.
  61563. * Default value is 0.975
  61564. * @type {number}
  61565. */
  61566. _this.area = 0.0075;
  61567. /**
  61568. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  61569. * Must not be equal to area and inferior to area.
  61570. * Default value is 0.0
  61571. * @type {number}
  61572. */
  61573. _this.fallOff = 0.000001;
  61574. /**
  61575. * The base color of the SSAO post-process
  61576. * The final result is "base + ssao" between [0, 1]
  61577. * @type {number}
  61578. */
  61579. _this.base = 0.5;
  61580. _this._firstUpdate = true;
  61581. _this._scene = scene;
  61582. // Set up assets
  61583. _this._createRandomTexture();
  61584. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  61585. var ssaoRatio = ratio.ssaoRatio || ratio;
  61586. var combineRatio = ratio.combineRatio || ratio;
  61587. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61588. _this._createSSAOPostProcess(ssaoRatio);
  61589. _this._createBlurPostProcess(ssaoRatio);
  61590. _this._createSSAOCombinePostProcess(combineRatio);
  61591. // Set up pipeline
  61592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61595. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61596. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61597. // Finish
  61598. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61599. if (cameras)
  61600. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61601. return _this;
  61602. }
  61603. // Public Methods
  61604. /**
  61605. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61606. */
  61607. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  61608. if (disableDepthRender === void 0) { disableDepthRender = false; }
  61609. for (var i = 0; i < this._scene.cameras.length; i++) {
  61610. var camera = this._scene.cameras[i];
  61611. this._originalColorPostProcess.dispose(camera);
  61612. this._ssaoPostProcess.dispose(camera);
  61613. this._blurHPostProcess.dispose(camera);
  61614. this._blurVPostProcess.dispose(camera);
  61615. this._ssaoCombinePostProcess.dispose(camera);
  61616. }
  61617. this._randomTexture.dispose();
  61618. if (disableDepthRender)
  61619. this._scene.disableDepthRenderer();
  61620. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61621. _super.prototype.dispose.call(this);
  61622. };
  61623. // Private Methods
  61624. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  61625. var _this = this;
  61626. var size = 16;
  61627. 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);
  61628. 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);
  61629. this._blurHPostProcess.onActivateObservable.add(function () {
  61630. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  61631. _this._blurHPostProcess.kernel = size * dw;
  61632. });
  61633. this._blurVPostProcess.onActivateObservable.add(function () {
  61634. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  61635. _this._blurVPostProcess.kernel = size * dw;
  61636. });
  61637. };
  61638. SSAORenderingPipeline.prototype._rebuild = function () {
  61639. this._firstUpdate = true;
  61640. _super.prototype._rebuild.call(this);
  61641. };
  61642. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61643. var _this = this;
  61644. var numSamples = 16;
  61645. var sampleSphere = [
  61646. 0.5381, 0.1856, -0.4319,
  61647. 0.1379, 0.2486, 0.4430,
  61648. 0.3371, 0.5679, -0.0057,
  61649. -0.6999, -0.0451, -0.0019,
  61650. 0.0689, -0.1598, -0.8547,
  61651. 0.0560, 0.0069, -0.1843,
  61652. -0.0146, 0.1402, 0.0762,
  61653. 0.0100, -0.1924, -0.0344,
  61654. -0.3577, -0.5301, -0.4358,
  61655. -0.3169, 0.1063, 0.0158,
  61656. 0.0103, -0.5869, 0.0046,
  61657. -0.0897, -0.4940, 0.3287,
  61658. 0.7119, -0.0154, -0.0918,
  61659. -0.0533, 0.0596, -0.5411,
  61660. 0.0352, -0.0631, 0.5460,
  61661. -0.4776, 0.2847, -0.0271
  61662. ];
  61663. var samplesFactor = 1.0 / numSamples;
  61664. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  61665. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61666. "area", "fallOff", "base", "range", "viewport"
  61667. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61668. this._ssaoPostProcess.onApply = function (effect) {
  61669. if (_this._firstUpdate) {
  61670. effect.setArray3("sampleSphere", sampleSphere);
  61671. effect.setFloat("samplesFactor", samplesFactor);
  61672. effect.setFloat("randTextureTiles", 4.0);
  61673. }
  61674. effect.setFloat("totalStrength", _this.totalStrength);
  61675. effect.setFloat("radius", _this.radius);
  61676. effect.setFloat("area", _this.area);
  61677. effect.setFloat("fallOff", _this.fallOff);
  61678. effect.setFloat("base", _this.base);
  61679. effect.setTexture("textureSampler", _this._depthTexture);
  61680. effect.setTexture("randomSampler", _this._randomTexture);
  61681. };
  61682. };
  61683. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61684. var _this = this;
  61685. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61686. this._ssaoCombinePostProcess.onApply = function (effect) {
  61687. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61688. };
  61689. };
  61690. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  61691. var size = 512;
  61692. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61693. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61694. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61695. var context = this._randomTexture.getContext();
  61696. var rand = function (min, max) {
  61697. return Math.random() * (max - min) + min;
  61698. };
  61699. var randVector = BABYLON.Vector3.Zero();
  61700. for (var x = 0; x < size; x++) {
  61701. for (var y = 0; y < size; y++) {
  61702. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  61703. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  61704. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  61705. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  61706. context.fillRect(x, y, 1, 1);
  61707. }
  61708. }
  61709. this._randomTexture.update(false);
  61710. };
  61711. __decorate([
  61712. BABYLON.serialize()
  61713. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  61714. __decorate([
  61715. BABYLON.serialize()
  61716. ], SSAORenderingPipeline.prototype, "radius", void 0);
  61717. __decorate([
  61718. BABYLON.serialize()
  61719. ], SSAORenderingPipeline.prototype, "area", void 0);
  61720. __decorate([
  61721. BABYLON.serialize()
  61722. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  61723. __decorate([
  61724. BABYLON.serialize()
  61725. ], SSAORenderingPipeline.prototype, "base", void 0);
  61726. return SSAORenderingPipeline;
  61727. }(BABYLON.PostProcessRenderPipeline));
  61728. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  61729. })(BABYLON || (BABYLON = {}));
  61730. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  61731. var BABYLON;
  61732. (function (BABYLON) {
  61733. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  61734. __extends(SSAO2RenderingPipeline, _super);
  61735. /**
  61736. * @constructor
  61737. * @param {string} name - The rendering pipeline name
  61738. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61739. * @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 }
  61740. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61741. */
  61742. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  61743. var _this = _super.call(this, scene.getEngine(), name) || this;
  61744. // Members
  61745. /**
  61746. * The PassPostProcess id in the pipeline that contains the original scene color
  61747. * @type {string}
  61748. */
  61749. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61750. /**
  61751. * The SSAO PostProcess id in the pipeline
  61752. * @type {string}
  61753. */
  61754. _this.SSAORenderEffect = "SSAORenderEffect";
  61755. /**
  61756. * The horizontal blur PostProcess id in the pipeline
  61757. * @type {string}
  61758. */
  61759. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61760. /**
  61761. * The vertical blur PostProcess id in the pipeline
  61762. * @type {string}
  61763. */
  61764. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61765. /**
  61766. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61767. * @type {string}
  61768. */
  61769. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61770. /**
  61771. * The output strength of the SSAO post-process. Default value is 1.0.
  61772. * @type {number}
  61773. */
  61774. _this.totalStrength = 1.0;
  61775. /**
  61776. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  61777. * @type {number}
  61778. */
  61779. _this.maxZ = 100.0;
  61780. /**
  61781. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  61782. * @type {number}
  61783. */
  61784. _this.minZAspect = 0.2;
  61785. /**
  61786. * Number of samples used for the SSAO calculations. Default value is 8
  61787. * @type {number}
  61788. */
  61789. _this._samples = 8;
  61790. /**
  61791. * Are we using bilateral blur ?
  61792. * @type {boolean}
  61793. */
  61794. _this._expensiveBlur = true;
  61795. /**
  61796. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  61797. * @type {number}
  61798. */
  61799. _this.radius = 2.0;
  61800. /**
  61801. * The base color of the SSAO post-process
  61802. * The final result is "base + ssao" between [0, 1]
  61803. * @type {number}
  61804. */
  61805. _this.base = 0.1;
  61806. _this._firstUpdate = true;
  61807. _this._scene = scene;
  61808. if (!_this.isSupported) {
  61809. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  61810. return _this;
  61811. }
  61812. var ssaoRatio = ratio.ssaoRatio || ratio;
  61813. var blurRatio = ratio.blurRatio || ratio;
  61814. // Set up assets
  61815. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  61816. _this._createRandomTexture();
  61817. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  61818. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  61819. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61820. _this._createSSAOPostProcess(1.0);
  61821. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  61822. _this._createSSAOCombinePostProcess(blurRatio);
  61823. // Set up pipeline
  61824. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61825. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61826. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61827. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61828. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61829. // Finish
  61830. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61831. if (cameras)
  61832. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61833. return _this;
  61834. }
  61835. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  61836. get: function () {
  61837. return this._samples;
  61838. },
  61839. set: function (n) {
  61840. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  61841. this._samples = n;
  61842. this._sampleSphere = this._generateHemisphere();
  61843. this._firstUpdate = true;
  61844. },
  61845. enumerable: true,
  61846. configurable: true
  61847. });
  61848. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  61849. get: function () {
  61850. return this._expensiveBlur;
  61851. },
  61852. set: function (b) {
  61853. 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"]);
  61854. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  61855. this._expensiveBlur = b;
  61856. this._firstUpdate = true;
  61857. },
  61858. enumerable: true,
  61859. configurable: true
  61860. });
  61861. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  61862. /**
  61863. * Support test.
  61864. * @type {boolean}
  61865. */
  61866. get: function () {
  61867. var engine = BABYLON.Engine.LastCreatedEngine;
  61868. if (!engine) {
  61869. return false;
  61870. }
  61871. return engine.getCaps().drawBuffersExtension;
  61872. },
  61873. enumerable: true,
  61874. configurable: true
  61875. });
  61876. // Public Methods
  61877. /**
  61878. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61879. */
  61880. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  61881. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  61882. for (var i = 0; i < this._scene.cameras.length; i++) {
  61883. var camera = this._scene.cameras[i];
  61884. this._originalColorPostProcess.dispose(camera);
  61885. this._ssaoPostProcess.dispose(camera);
  61886. this._blurHPostProcess.dispose(camera);
  61887. this._blurVPostProcess.dispose(camera);
  61888. this._ssaoCombinePostProcess.dispose(camera);
  61889. }
  61890. this._randomTexture.dispose();
  61891. if (disableGeometryBufferRenderer)
  61892. this._scene.disableGeometryBufferRenderer();
  61893. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61894. _super.prototype.dispose.call(this);
  61895. };
  61896. // Private Methods
  61897. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  61898. var _this = this;
  61899. this._samplerOffsets = [];
  61900. var expensive = this.expensiveBlur;
  61901. for (var i = -8; i < 8; i++) {
  61902. this._samplerOffsets.push(i * 2 + 0.5);
  61903. }
  61904. 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");
  61905. this._blurHPostProcess.onApply = function (effect) {
  61906. if (!_this._scene.activeCamera) {
  61907. return;
  61908. }
  61909. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  61910. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61911. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61912. effect.setFloat("radius", _this.radius);
  61913. effect.setTexture("depthSampler", _this._depthTexture);
  61914. if (_this._firstUpdate) {
  61915. effect.setArray("samplerOffsets", _this._samplerOffsets);
  61916. }
  61917. };
  61918. 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");
  61919. this._blurVPostProcess.onApply = function (effect) {
  61920. if (!_this._scene.activeCamera) {
  61921. return;
  61922. }
  61923. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  61924. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61925. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61926. effect.setFloat("radius", _this.radius);
  61927. effect.setTexture("depthSampler", _this._depthTexture);
  61928. if (_this._firstUpdate) {
  61929. effect.setArray("samplerOffsets", _this._samplerOffsets);
  61930. _this._firstUpdate = false;
  61931. }
  61932. };
  61933. };
  61934. SSAO2RenderingPipeline.prototype._rebuild = function () {
  61935. this._firstUpdate = true;
  61936. _super.prototype._rebuild.call(this);
  61937. };
  61938. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  61939. var numSamples = this.samples;
  61940. var result = [];
  61941. var vector, scale;
  61942. var rand = function (min, max) {
  61943. return Math.random() * (max - min) + min;
  61944. };
  61945. var i = 0;
  61946. while (i < numSamples) {
  61947. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  61948. vector.normalize();
  61949. scale = i / numSamples;
  61950. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  61951. vector.scaleInPlace(scale);
  61952. result.push(vector.x, vector.y, vector.z);
  61953. i++;
  61954. }
  61955. return result;
  61956. };
  61957. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61958. var _this = this;
  61959. var numSamples = this.samples;
  61960. this._sampleSphere = this._generateHemisphere();
  61961. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  61962. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61963. "base", "range", "projection", "near", "far", "texelSize",
  61964. "xViewport", "yViewport", "maxZ", "minZAspect"
  61965. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61966. this._ssaoPostProcess.onApply = function (effect) {
  61967. if (_this._firstUpdate) {
  61968. effect.setArray3("sampleSphere", _this._sampleSphere);
  61969. effect.setFloat("randTextureTiles", 4.0);
  61970. }
  61971. if (!_this._scene.activeCamera) {
  61972. return;
  61973. }
  61974. effect.setFloat("samplesFactor", 1 / _this.samples);
  61975. effect.setFloat("totalStrength", _this.totalStrength);
  61976. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  61977. effect.setFloat("radius", _this.radius);
  61978. effect.setFloat("maxZ", _this.maxZ);
  61979. effect.setFloat("minZAspect", _this.minZAspect);
  61980. effect.setFloat("base", _this.base);
  61981. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61982. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61983. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  61984. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  61985. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  61986. effect.setTexture("textureSampler", _this._depthTexture);
  61987. effect.setTexture("normalSampler", _this._normalTexture);
  61988. effect.setTexture("randomSampler", _this._randomTexture);
  61989. };
  61990. };
  61991. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61992. var _this = this;
  61993. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61994. this._ssaoCombinePostProcess.onApply = function (effect) {
  61995. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61996. };
  61997. };
  61998. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  61999. var size = 512;
  62000. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62001. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62002. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62003. var context = this._randomTexture.getContext();
  62004. var rand = function (min, max) {
  62005. return Math.random() * (max - min) + min;
  62006. };
  62007. var randVector = BABYLON.Vector3.Zero();
  62008. for (var x = 0; x < size; x++) {
  62009. for (var y = 0; y < size; y++) {
  62010. randVector.x = rand(0.0, 1.0);
  62011. randVector.y = rand(0.0, 1.0);
  62012. randVector.z = 0.0;
  62013. randVector.normalize();
  62014. randVector.scaleInPlace(255);
  62015. randVector.x = Math.floor(randVector.x);
  62016. randVector.y = Math.floor(randVector.y);
  62017. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62018. context.fillRect(x, y, 1, 1);
  62019. }
  62020. }
  62021. this._randomTexture.update(false);
  62022. };
  62023. __decorate([
  62024. BABYLON.serialize()
  62025. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62026. __decorate([
  62027. BABYLON.serialize()
  62028. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62029. __decorate([
  62030. BABYLON.serialize()
  62031. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62032. __decorate([
  62033. BABYLON.serialize("samples")
  62034. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62035. __decorate([
  62036. BABYLON.serialize("expensiveBlur")
  62037. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62038. __decorate([
  62039. BABYLON.serialize()
  62040. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62041. __decorate([
  62042. BABYLON.serialize()
  62043. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62044. return SSAO2RenderingPipeline;
  62045. }(BABYLON.PostProcessRenderPipeline));
  62046. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62047. })(BABYLON || (BABYLON = {}));
  62048. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62049. // BABYLON.JS Chromatic Aberration GLSL Shader
  62050. // Author: Olivier Guyot
  62051. // Separates very slightly R, G and B colors on the edges of the screen
  62052. // Inspired by Francois Tarlier & Martins Upitis
  62053. var BABYLON;
  62054. (function (BABYLON) {
  62055. var LensRenderingPipeline = /** @class */ (function (_super) {
  62056. __extends(LensRenderingPipeline, _super);
  62057. /**
  62058. * @constructor
  62059. *
  62060. * Effect parameters are as follow:
  62061. * {
  62062. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62063. * edge_blur: number; // from 0 to x (1 for realism)
  62064. * distortion: number; // from 0 to x (1 for realism)
  62065. * grain_amount: number; // from 0 to 1
  62066. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62067. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62068. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62069. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62070. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62071. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62072. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62073. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62074. * }
  62075. * Note: if an effect parameter is unset, effect is disabled
  62076. *
  62077. * @param {string} name - The rendering pipeline name
  62078. * @param {object} parameters - An object containing all parameters (see above)
  62079. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62080. * @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)
  62081. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62082. */
  62083. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62084. if (ratio === void 0) { ratio = 1.0; }
  62085. var _this = _super.call(this, scene.getEngine(), name) || this;
  62086. // Lens effects can be of the following:
  62087. // - chromatic aberration (slight shift of RGB colors)
  62088. // - blur on the edge of the lens
  62089. // - lens distortion
  62090. // - depth-of-field blur & highlights enhancing
  62091. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62092. // - grain effect (noise or custom texture)
  62093. // Two additional texture samplers are needed:
  62094. // - depth map (for depth-of-field)
  62095. // - grain texture
  62096. /**
  62097. * The chromatic aberration PostProcess id in the pipeline
  62098. * @type {string}
  62099. */
  62100. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62101. /**
  62102. * The highlights enhancing PostProcess id in the pipeline
  62103. * @type {string}
  62104. */
  62105. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62106. /**
  62107. * The depth-of-field PostProcess id in the pipeline
  62108. * @type {string}
  62109. */
  62110. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62111. _this._scene = scene;
  62112. // Fetch texture samplers
  62113. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62114. if (parameters.grain_texture) {
  62115. _this._grainTexture = parameters.grain_texture;
  62116. }
  62117. else {
  62118. _this._createGrainTexture();
  62119. }
  62120. // save parameters
  62121. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62122. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62123. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62124. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62125. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62126. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62127. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62128. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62129. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62130. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62131. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62132. // Create effects
  62133. _this._createChromaticAberrationPostProcess(ratio);
  62134. _this._createHighlightsPostProcess(ratio);
  62135. _this._createDepthOfFieldPostProcess(ratio / 4);
  62136. // Set up pipeline
  62137. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62138. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62139. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62140. if (_this._highlightsGain === -1) {
  62141. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62142. }
  62143. // Finish
  62144. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62145. if (cameras) {
  62146. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62147. }
  62148. return _this;
  62149. }
  62150. // public methods (self explanatory)
  62151. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62152. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62153. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62154. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62155. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62156. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62157. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62158. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62159. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62160. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62161. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62162. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62163. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62164. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62165. };
  62166. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62167. this._highlightsPostProcess.updateEffect();
  62168. };
  62169. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62170. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62171. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62172. this._highlightsGain = amount;
  62173. };
  62174. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62175. if (this._highlightsGain === -1) {
  62176. this._highlightsGain = 1.0;
  62177. }
  62178. this._highlightsThreshold = amount;
  62179. };
  62180. LensRenderingPipeline.prototype.disableHighlights = function () {
  62181. this._highlightsGain = -1;
  62182. };
  62183. /**
  62184. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62185. */
  62186. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62187. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62188. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62189. this._chromaticAberrationPostProcess = null;
  62190. this._highlightsPostProcess = null;
  62191. this._depthOfFieldPostProcess = null;
  62192. this._grainTexture.dispose();
  62193. if (disableDepthRender)
  62194. this._scene.disableDepthRenderer();
  62195. };
  62196. // colors shifting and distortion
  62197. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62198. var _this = this;
  62199. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62200. [], // samplers
  62201. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62202. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62203. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62204. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62205. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62206. };
  62207. };
  62208. // highlights enhancing
  62209. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62210. var _this = this;
  62211. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62212. [], // samplers
  62213. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62214. this._highlightsPostProcess.onApply = function (effect) {
  62215. effect.setFloat('gain', _this._highlightsGain);
  62216. effect.setFloat('threshold', _this._highlightsThreshold);
  62217. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62218. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62219. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62220. };
  62221. };
  62222. // colors shifting and distortion
  62223. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62224. var _this = this;
  62225. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62226. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62227. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62228. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62229. this._depthOfFieldPostProcess.onApply = function (effect) {
  62230. effect.setTexture("depthSampler", _this._depthTexture);
  62231. effect.setTexture("grainSampler", _this._grainTexture);
  62232. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62233. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62234. effect.setFloat('grain_amount', _this._grainAmount);
  62235. effect.setBool('blur_noise', _this._blurNoise);
  62236. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62237. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62238. effect.setFloat('distortion', _this._distortion);
  62239. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62240. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62241. effect.setFloat('aperture', _this._dofAperture);
  62242. effect.setFloat('darken', _this._dofDarken);
  62243. effect.setFloat('edge_blur', _this._edgeBlur);
  62244. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62245. if (_this._scene.activeCamera) {
  62246. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62247. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62248. }
  62249. };
  62250. };
  62251. // creates a black and white random noise texture, 512x512
  62252. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62253. var size = 512;
  62254. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62255. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62256. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62257. var context = this._grainTexture.getContext();
  62258. var rand = function (min, max) {
  62259. return Math.random() * (max - min) + min;
  62260. };
  62261. var value;
  62262. for (var x = 0; x < size; x++) {
  62263. for (var y = 0; y < size; y++) {
  62264. value = Math.floor(rand(0.42, 0.58) * 255);
  62265. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62266. context.fillRect(x, y, 1, 1);
  62267. }
  62268. }
  62269. this._grainTexture.update(false);
  62270. };
  62271. return LensRenderingPipeline;
  62272. }(BABYLON.PostProcessRenderPipeline));
  62273. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62274. })(BABYLON || (BABYLON = {}));
  62275. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62276. var BABYLON;
  62277. (function (BABYLON) {
  62278. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62279. __extends(StandardRenderingPipeline, _super);
  62280. /**
  62281. * @constructor
  62282. * @param {string} name - The rendering pipeline name
  62283. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62284. * @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)
  62285. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62286. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62287. */
  62288. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62289. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62290. var _this = _super.call(this, scene.getEngine(), name) || this;
  62291. _this.downSampleX4PostProcess = null;
  62292. _this.brightPassPostProcess = null;
  62293. _this.blurHPostProcesses = [];
  62294. _this.blurVPostProcesses = [];
  62295. _this.textureAdderPostProcess = null;
  62296. _this.volumetricLightPostProcess = null;
  62297. _this.volumetricLightSmoothXPostProcess = null;
  62298. _this.volumetricLightSmoothYPostProcess = null;
  62299. _this.volumetricLightMergePostProces = null;
  62300. _this.volumetricLightFinalPostProcess = null;
  62301. _this.luminancePostProcess = null;
  62302. _this.luminanceDownSamplePostProcesses = [];
  62303. _this.hdrPostProcess = null;
  62304. _this.textureAdderFinalPostProcess = null;
  62305. _this.lensFlareFinalPostProcess = null;
  62306. _this.hdrFinalPostProcess = null;
  62307. _this.lensFlarePostProcess = null;
  62308. _this.lensFlareComposePostProcess = null;
  62309. _this.motionBlurPostProcess = null;
  62310. _this.depthOfFieldPostProcess = null;
  62311. // Values
  62312. _this.brightThreshold = 1.0;
  62313. _this.blurWidth = 512.0;
  62314. _this.horizontalBlur = false;
  62315. _this.exposure = 1.0;
  62316. _this.lensTexture = null;
  62317. _this.volumetricLightCoefficient = 0.2;
  62318. _this.volumetricLightPower = 4.0;
  62319. _this.volumetricLightBlurScale = 64.0;
  62320. _this.sourceLight = null;
  62321. _this.hdrMinimumLuminance = 1.0;
  62322. _this.hdrDecreaseRate = 0.5;
  62323. _this.hdrIncreaseRate = 0.5;
  62324. _this.lensColorTexture = null;
  62325. _this.lensFlareStrength = 20.0;
  62326. _this.lensFlareGhostDispersal = 1.4;
  62327. _this.lensFlareHaloWidth = 0.7;
  62328. _this.lensFlareDistortionStrength = 16.0;
  62329. _this.lensStarTexture = null;
  62330. _this.lensFlareDirtTexture = null;
  62331. _this.depthOfFieldDistance = 10.0;
  62332. _this.depthOfFieldBlurWidth = 64.0;
  62333. _this.motionStrength = 1.0;
  62334. // IAnimatable
  62335. _this.animations = [];
  62336. _this._currentDepthOfFieldSource = null;
  62337. _this._hdrCurrentLuminance = 1.0;
  62338. // Getters and setters
  62339. _this._bloomEnabled = true;
  62340. _this._depthOfFieldEnabled = false;
  62341. _this._vlsEnabled = false;
  62342. _this._lensFlareEnabled = false;
  62343. _this._hdrEnabled = false;
  62344. _this._motionBlurEnabled = false;
  62345. _this._motionBlurSamples = 64.0;
  62346. _this._volumetricLightStepsCount = 50.0;
  62347. _this._cameras = cameras || [];
  62348. // Initialize
  62349. _this._scene = scene;
  62350. _this._basePostProcess = originalPostProcess;
  62351. _this._ratio = ratio;
  62352. // Misc
  62353. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62354. // Finish
  62355. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62356. _this._buildPipeline();
  62357. return _this;
  62358. }
  62359. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62360. get: function () {
  62361. return this._bloomEnabled;
  62362. },
  62363. set: function (enabled) {
  62364. if (this._bloomEnabled === enabled) {
  62365. return;
  62366. }
  62367. this._bloomEnabled = enabled;
  62368. this._buildPipeline();
  62369. },
  62370. enumerable: true,
  62371. configurable: true
  62372. });
  62373. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62374. get: function () {
  62375. return this._depthOfFieldEnabled;
  62376. },
  62377. set: function (enabled) {
  62378. if (this._depthOfFieldEnabled === enabled) {
  62379. return;
  62380. }
  62381. this._depthOfFieldEnabled = enabled;
  62382. this._buildPipeline();
  62383. },
  62384. enumerable: true,
  62385. configurable: true
  62386. });
  62387. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62388. get: function () {
  62389. return this._lensFlareEnabled;
  62390. },
  62391. set: function (enabled) {
  62392. if (this._lensFlareEnabled === enabled) {
  62393. return;
  62394. }
  62395. this._lensFlareEnabled = enabled;
  62396. this._buildPipeline();
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62402. get: function () {
  62403. return this._hdrEnabled;
  62404. },
  62405. set: function (enabled) {
  62406. if (this._hdrEnabled === enabled) {
  62407. return;
  62408. }
  62409. this._hdrEnabled = enabled;
  62410. this._buildPipeline();
  62411. },
  62412. enumerable: true,
  62413. configurable: true
  62414. });
  62415. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62416. get: function () {
  62417. return this._vlsEnabled;
  62418. },
  62419. set: function (enabled) {
  62420. if (this._vlsEnabled === enabled) {
  62421. return;
  62422. }
  62423. if (enabled) {
  62424. var geometry = this._scene.enableGeometryBufferRenderer();
  62425. if (!geometry) {
  62426. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62427. return;
  62428. }
  62429. }
  62430. this._vlsEnabled = enabled;
  62431. this._buildPipeline();
  62432. },
  62433. enumerable: true,
  62434. configurable: true
  62435. });
  62436. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62437. get: function () {
  62438. return this._motionBlurEnabled;
  62439. },
  62440. set: function (enabled) {
  62441. if (this._motionBlurEnabled === enabled) {
  62442. return;
  62443. }
  62444. this._motionBlurEnabled = enabled;
  62445. this._buildPipeline();
  62446. },
  62447. enumerable: true,
  62448. configurable: true
  62449. });
  62450. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62451. get: function () {
  62452. return this._volumetricLightStepsCount;
  62453. },
  62454. set: function (count) {
  62455. if (this.volumetricLightPostProcess) {
  62456. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62457. }
  62458. this._volumetricLightStepsCount = count;
  62459. },
  62460. enumerable: true,
  62461. configurable: true
  62462. });
  62463. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62464. get: function () {
  62465. return this._motionBlurSamples;
  62466. },
  62467. set: function (samples) {
  62468. if (this.motionBlurPostProcess) {
  62469. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  62470. }
  62471. this._motionBlurSamples = samples;
  62472. },
  62473. enumerable: true,
  62474. configurable: true
  62475. });
  62476. StandardRenderingPipeline.prototype._buildPipeline = function () {
  62477. var _this = this;
  62478. var ratio = this._ratio;
  62479. var scene = this._scene;
  62480. this._disposePostProcesses();
  62481. this._reset();
  62482. // Create pass post-process
  62483. if (!this._basePostProcess) {
  62484. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  62485. this.originalPostProcess.onApply = function (effect) {
  62486. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  62487. };
  62488. }
  62489. else {
  62490. this.originalPostProcess = this._basePostProcess;
  62491. }
  62492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62493. this._currentDepthOfFieldSource = this.originalPostProcess;
  62494. if (this._vlsEnabled) {
  62495. // Create volumetric light
  62496. this._createVolumetricLightPostProcess(scene, ratio);
  62497. // Create volumetric light final post-process
  62498. 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);
  62499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  62500. }
  62501. if (this._bloomEnabled) {
  62502. // Create down sample X4 post-process
  62503. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62504. // Create bright pass post-process
  62505. this._createBrightPassPostProcess(scene, ratio / 2);
  62506. // Create gaussian blur post-processes (down sampling blurs)
  62507. this._createBlurPostProcesses(scene, ratio / 4, 1);
  62508. // Create texture adder post-process
  62509. this._createTextureAdderPostProcess(scene, ratio);
  62510. // Create depth-of-field source post-process
  62511. 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);
  62512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  62513. }
  62514. if (this._lensFlareEnabled) {
  62515. // Create lens flare post-process
  62516. this._createLensFlarePostProcess(scene, ratio);
  62517. // Create depth-of-field source post-process post lens-flare and disable it now
  62518. 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);
  62519. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  62520. }
  62521. if (this._hdrEnabled) {
  62522. // Create luminance
  62523. this._createLuminancePostProcesses(scene, this._floatTextureType);
  62524. // Create HDR
  62525. this._createHdrPostProcess(scene, ratio);
  62526. // Create depth-of-field source post-process post hdr and disable it now
  62527. 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);
  62528. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  62529. }
  62530. if (this._depthOfFieldEnabled) {
  62531. // Create gaussian blur used by depth-of-field
  62532. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  62533. // Create depth-of-field post-process
  62534. this._createDepthOfFieldPostProcess(scene, ratio);
  62535. }
  62536. if (this._motionBlurEnabled) {
  62537. // Create motion blur post-process
  62538. this._createMotionBlurPostProcess(scene, ratio);
  62539. }
  62540. if (this._cameras !== null) {
  62541. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  62542. }
  62543. };
  62544. // Down Sample X4 Post-Processs
  62545. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62546. var _this = this;
  62547. var downSampleX4Offsets = new Array(32);
  62548. 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);
  62549. this.downSampleX4PostProcess.onApply = function (effect) {
  62550. var id = 0;
  62551. var width = _this.downSampleX4PostProcess.width;
  62552. var height = _this.downSampleX4PostProcess.height;
  62553. for (var i = -2; i < 2; i++) {
  62554. for (var j = -2; j < 2; j++) {
  62555. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  62556. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  62557. id += 2;
  62558. }
  62559. }
  62560. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62561. };
  62562. // Add to pipeline
  62563. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62564. };
  62565. // Brightpass Post-Process
  62566. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62567. var _this = this;
  62568. var brightOffsets = new Array(8);
  62569. 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);
  62570. this.brightPassPostProcess.onApply = function (effect) {
  62571. var sU = (1.0 / _this.brightPassPostProcess.width);
  62572. var sV = (1.0 / _this.brightPassPostProcess.height);
  62573. brightOffsets[0] = -0.5 * sU;
  62574. brightOffsets[1] = 0.5 * sV;
  62575. brightOffsets[2] = 0.5 * sU;
  62576. brightOffsets[3] = 0.5 * sV;
  62577. brightOffsets[4] = -0.5 * sU;
  62578. brightOffsets[5] = -0.5 * sV;
  62579. brightOffsets[6] = 0.5 * sU;
  62580. brightOffsets[7] = -0.5 * sV;
  62581. effect.setArray2("dsOffsets", brightOffsets);
  62582. effect.setFloat("brightThreshold", _this.brightThreshold);
  62583. };
  62584. // Add to pipeline
  62585. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62586. };
  62587. // Create blur H&V post-processes
  62588. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  62589. var _this = this;
  62590. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  62591. var engine = scene.getEngine();
  62592. 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);
  62593. 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);
  62594. blurX.onActivateObservable.add(function () {
  62595. var dw = blurX.width / engine.getRenderWidth();
  62596. blurX.kernel = _this[blurWidthKey] * dw;
  62597. });
  62598. blurY.onActivateObservable.add(function () {
  62599. var dw = blurY.height / engine.getRenderHeight();
  62600. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  62601. });
  62602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  62603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  62604. this.blurHPostProcesses.push(blurX);
  62605. this.blurVPostProcesses.push(blurY);
  62606. };
  62607. // Create texture adder post-process
  62608. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62609. var _this = this;
  62610. 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);
  62611. this.textureAdderPostProcess.onApply = function (effect) {
  62612. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  62613. effect.setTexture("lensSampler", _this.lensTexture);
  62614. effect.setFloat("exposure", _this.exposure);
  62615. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  62616. };
  62617. // Add to pipeline
  62618. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62619. };
  62620. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  62621. var _this = this;
  62622. var geometryRenderer = scene.enableGeometryBufferRenderer();
  62623. geometryRenderer.enablePosition = true;
  62624. var geometry = geometryRenderer.getGBuffer();
  62625. // Base post-process
  62626. 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));
  62627. var depthValues = BABYLON.Vector2.Zero();
  62628. this.volumetricLightPostProcess.onApply = function (effect) {
  62629. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  62630. var generator = _this.sourceLight.getShadowGenerator();
  62631. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  62632. effect.setTexture("positionSampler", geometry.textures[2]);
  62633. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  62634. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  62635. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  62636. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  62637. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  62638. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  62639. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  62640. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  62641. effect.setVector2("depthValues", depthValues);
  62642. }
  62643. };
  62644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  62645. // Smooth
  62646. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  62647. // Merge
  62648. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  62649. this.volumetricLightMergePostProces.onApply = function (effect) {
  62650. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  62651. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  62652. };
  62653. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  62654. };
  62655. // Create luminance
  62656. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  62657. var _this = this;
  62658. // Create luminance
  62659. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  62660. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  62661. var offsets = [];
  62662. this.luminancePostProcess.onApply = function (effect) {
  62663. var sU = (1.0 / _this.luminancePostProcess.width);
  62664. var sV = (1.0 / _this.luminancePostProcess.height);
  62665. offsets[0] = -0.5 * sU;
  62666. offsets[1] = 0.5 * sV;
  62667. offsets[2] = 0.5 * sU;
  62668. offsets[3] = 0.5 * sV;
  62669. offsets[4] = -0.5 * sU;
  62670. offsets[5] = -0.5 * sV;
  62671. offsets[6] = 0.5 * sU;
  62672. offsets[7] = -0.5 * sV;
  62673. effect.setArray2("lumOffsets", offsets);
  62674. };
  62675. // Add to pipeline
  62676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  62677. // Create down sample luminance
  62678. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  62679. var size = Math.pow(3, i);
  62680. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  62681. if (i === 0) {
  62682. defines += "#define FINAL_DOWN_SAMPLER";
  62683. }
  62684. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  62685. this.luminanceDownSamplePostProcesses.push(postProcess);
  62686. }
  62687. // Create callbacks and add effects
  62688. var lastLuminance = this.luminancePostProcess;
  62689. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  62690. var downSampleOffsets = new Array(18);
  62691. pp.onApply = function (effect) {
  62692. if (!lastLuminance) {
  62693. return;
  62694. }
  62695. var id = 0;
  62696. for (var x = -1; x < 2; x++) {
  62697. for (var y = -1; y < 2; y++) {
  62698. downSampleOffsets[id] = x / lastLuminance.width;
  62699. downSampleOffsets[id + 1] = y / lastLuminance.height;
  62700. id += 2;
  62701. }
  62702. }
  62703. effect.setArray2("dsOffsets", downSampleOffsets);
  62704. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  62705. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62706. lastLuminance = _this.luminancePostProcess;
  62707. }
  62708. else {
  62709. lastLuminance = pp;
  62710. }
  62711. };
  62712. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62713. pp.onAfterRender = function (effect) {
  62714. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  62715. 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);
  62716. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  62717. };
  62718. }
  62719. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  62720. });
  62721. };
  62722. // Create HDR post-process
  62723. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  62724. var _this = this;
  62725. 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);
  62726. var outputLiminance = 1;
  62727. var time = 0;
  62728. var lastTime = 0;
  62729. this.hdrPostProcess.onApply = function (effect) {
  62730. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  62731. time += scene.getEngine().getDeltaTime();
  62732. if (outputLiminance < 0) {
  62733. outputLiminance = _this._hdrCurrentLuminance;
  62734. }
  62735. else {
  62736. var dt = (lastTime - time) / 1000.0;
  62737. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  62738. outputLiminance += _this.hdrDecreaseRate * dt;
  62739. }
  62740. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  62741. outputLiminance -= _this.hdrIncreaseRate * dt;
  62742. }
  62743. else {
  62744. outputLiminance = _this._hdrCurrentLuminance;
  62745. }
  62746. }
  62747. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  62748. effect.setFloat("averageLuminance", outputLiminance);
  62749. lastTime = time;
  62750. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  62751. };
  62752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  62753. };
  62754. // Create lens flare post-process
  62755. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  62756. var _this = this;
  62757. 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);
  62758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  62759. this._createBlurPostProcesses(scene, ratio / 4, 2);
  62760. 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);
  62761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  62762. var resolution = new BABYLON.Vector2(0, 0);
  62763. // Lens flare
  62764. this.lensFlarePostProcess.onApply = function (effect) {
  62765. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  62766. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  62767. effect.setFloat("strength", _this.lensFlareStrength);
  62768. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  62769. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  62770. // Shift
  62771. resolution.x = _this.lensFlarePostProcess.width;
  62772. resolution.y = _this.lensFlarePostProcess.height;
  62773. effect.setVector2("resolution", resolution);
  62774. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  62775. };
  62776. // Compose
  62777. 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);
  62778. 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);
  62779. this.lensFlareComposePostProcess.onApply = function (effect) {
  62780. if (!_this._scene.activeCamera) {
  62781. return;
  62782. }
  62783. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62784. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  62785. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  62786. // Lens start rotation matrix
  62787. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  62788. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  62789. 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));
  62790. camRot *= 4.0;
  62791. 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);
  62792. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  62793. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  62794. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  62795. };
  62796. };
  62797. // Create depth-of-field post-process
  62798. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62799. var _this = this;
  62800. 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);
  62801. this.depthOfFieldPostProcess.onApply = function (effect) {
  62802. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62803. effect.setTexture("depthSampler", _this._getDepthTexture());
  62804. effect.setFloat("distance", _this.depthOfFieldDistance);
  62805. };
  62806. // Add to pipeline
  62807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62808. };
  62809. // Create motion blur post-process
  62810. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  62811. var _this = this;
  62812. 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);
  62813. var motionScale = 0;
  62814. var prevViewProjection = BABYLON.Matrix.Identity();
  62815. var invViewProjection = BABYLON.Matrix.Identity();
  62816. var viewProjection = BABYLON.Matrix.Identity();
  62817. var screenSize = BABYLON.Vector2.Zero();
  62818. this.motionBlurPostProcess.onApply = function (effect) {
  62819. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  62820. viewProjection.invertToRef(invViewProjection);
  62821. effect.setMatrix("inverseViewProjection", invViewProjection);
  62822. effect.setMatrix("prevViewProjection", prevViewProjection);
  62823. prevViewProjection = viewProjection;
  62824. screenSize.x = _this.motionBlurPostProcess.width;
  62825. screenSize.y = _this.motionBlurPostProcess.height;
  62826. effect.setVector2("screenSize", screenSize);
  62827. motionScale = scene.getEngine().getFps() / 60.0;
  62828. effect.setFloat("motionScale", motionScale);
  62829. effect.setFloat("motionStrength", _this.motionStrength);
  62830. effect.setTexture("depthSampler", _this._getDepthTexture());
  62831. };
  62832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  62833. };
  62834. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  62835. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  62836. var renderer = this._scene.enableGeometryBufferRenderer();
  62837. return renderer.getGBuffer().textures[0];
  62838. }
  62839. return this._scene.enableDepthRenderer().getDepthMap();
  62840. };
  62841. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  62842. for (var i = 0; i < this._cameras.length; i++) {
  62843. var camera = this._cameras[i];
  62844. if (this.originalPostProcess) {
  62845. this.originalPostProcess.dispose(camera);
  62846. }
  62847. if (this.downSampleX4PostProcess) {
  62848. this.downSampleX4PostProcess.dispose(camera);
  62849. }
  62850. if (this.brightPassPostProcess) {
  62851. this.brightPassPostProcess.dispose(camera);
  62852. }
  62853. if (this.textureAdderPostProcess) {
  62854. this.textureAdderPostProcess.dispose(camera);
  62855. }
  62856. if (this.textureAdderFinalPostProcess) {
  62857. this.textureAdderFinalPostProcess.dispose(camera);
  62858. }
  62859. if (this.volumetricLightPostProcess) {
  62860. this.volumetricLightPostProcess.dispose(camera);
  62861. }
  62862. if (this.volumetricLightSmoothXPostProcess) {
  62863. this.volumetricLightSmoothXPostProcess.dispose(camera);
  62864. }
  62865. if (this.volumetricLightSmoothYPostProcess) {
  62866. this.volumetricLightSmoothYPostProcess.dispose(camera);
  62867. }
  62868. if (this.volumetricLightMergePostProces) {
  62869. this.volumetricLightMergePostProces.dispose(camera);
  62870. }
  62871. if (this.volumetricLightFinalPostProcess) {
  62872. this.volumetricLightFinalPostProcess.dispose(camera);
  62873. }
  62874. if (this.lensFlarePostProcess) {
  62875. this.lensFlarePostProcess.dispose(camera);
  62876. }
  62877. if (this.lensFlareComposePostProcess) {
  62878. this.lensFlareComposePostProcess.dispose(camera);
  62879. }
  62880. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  62881. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  62882. }
  62883. if (this.luminancePostProcess) {
  62884. this.luminancePostProcess.dispose(camera);
  62885. }
  62886. if (this.hdrPostProcess) {
  62887. this.hdrPostProcess.dispose(camera);
  62888. }
  62889. if (this.hdrFinalPostProcess) {
  62890. this.hdrFinalPostProcess.dispose(camera);
  62891. }
  62892. if (this.depthOfFieldPostProcess) {
  62893. this.depthOfFieldPostProcess.dispose(camera);
  62894. }
  62895. if (this.motionBlurPostProcess) {
  62896. this.motionBlurPostProcess.dispose(camera);
  62897. }
  62898. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  62899. this.blurHPostProcesses[j].dispose(camera);
  62900. }
  62901. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  62902. this.blurVPostProcesses[j].dispose(camera);
  62903. }
  62904. }
  62905. this.originalPostProcess = null;
  62906. this.downSampleX4PostProcess = null;
  62907. this.brightPassPostProcess = null;
  62908. this.textureAdderPostProcess = null;
  62909. this.textureAdderFinalPostProcess = null;
  62910. this.volumetricLightPostProcess = null;
  62911. this.volumetricLightSmoothXPostProcess = null;
  62912. this.volumetricLightSmoothYPostProcess = null;
  62913. this.volumetricLightMergePostProces = null;
  62914. this.volumetricLightFinalPostProcess = null;
  62915. this.lensFlarePostProcess = null;
  62916. this.lensFlareComposePostProcess = null;
  62917. this.luminancePostProcess = null;
  62918. this.hdrPostProcess = null;
  62919. this.hdrFinalPostProcess = null;
  62920. this.depthOfFieldPostProcess = null;
  62921. this.motionBlurPostProcess = null;
  62922. this.luminanceDownSamplePostProcesses = [];
  62923. this.blurHPostProcesses = [];
  62924. this.blurVPostProcesses = [];
  62925. };
  62926. // Dispose
  62927. StandardRenderingPipeline.prototype.dispose = function () {
  62928. this._disposePostProcesses();
  62929. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  62930. _super.prototype.dispose.call(this);
  62931. };
  62932. // Serialize rendering pipeline
  62933. StandardRenderingPipeline.prototype.serialize = function () {
  62934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62935. serializationObject.customType = "StandardRenderingPipeline";
  62936. return serializationObject;
  62937. };
  62938. /**
  62939. * Static members
  62940. */
  62941. // Parse serialized pipeline
  62942. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  62943. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  62944. };
  62945. // Luminance steps
  62946. StandardRenderingPipeline.LuminanceSteps = 6;
  62947. __decorate([
  62948. BABYLON.serialize()
  62949. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  62950. __decorate([
  62951. BABYLON.serialize()
  62952. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  62953. __decorate([
  62954. BABYLON.serialize()
  62955. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  62956. __decorate([
  62957. BABYLON.serialize()
  62958. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  62959. __decorate([
  62960. BABYLON.serializeAsTexture("lensTexture")
  62961. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  62962. __decorate([
  62963. BABYLON.serialize()
  62964. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  62965. __decorate([
  62966. BABYLON.serialize()
  62967. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  62968. __decorate([
  62969. BABYLON.serialize()
  62970. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  62971. __decorate([
  62972. BABYLON.serialize()
  62973. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  62974. __decorate([
  62975. BABYLON.serialize()
  62976. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  62977. __decorate([
  62978. BABYLON.serialize()
  62979. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  62980. __decorate([
  62981. BABYLON.serializeAsTexture("lensColorTexture")
  62982. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  62983. __decorate([
  62984. BABYLON.serialize()
  62985. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  62986. __decorate([
  62987. BABYLON.serialize()
  62988. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  62989. __decorate([
  62990. BABYLON.serialize()
  62991. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  62992. __decorate([
  62993. BABYLON.serialize()
  62994. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  62995. __decorate([
  62996. BABYLON.serializeAsTexture("lensStarTexture")
  62997. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  62998. __decorate([
  62999. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63000. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63001. __decorate([
  63002. BABYLON.serialize()
  63003. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63004. __decorate([
  63005. BABYLON.serialize()
  63006. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63007. __decorate([
  63008. BABYLON.serialize()
  63009. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63010. __decorate([
  63011. BABYLON.serialize()
  63012. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63013. __decorate([
  63014. BABYLON.serialize()
  63015. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63016. __decorate([
  63017. BABYLON.serialize()
  63018. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63019. __decorate([
  63020. BABYLON.serialize()
  63021. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63022. __decorate([
  63023. BABYLON.serialize()
  63024. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63025. __decorate([
  63026. BABYLON.serialize()
  63027. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63028. __decorate([
  63029. BABYLON.serialize()
  63030. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63031. __decorate([
  63032. BABYLON.serialize()
  63033. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63034. __decorate([
  63035. BABYLON.serialize()
  63036. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63037. return StandardRenderingPipeline;
  63038. }(BABYLON.PostProcessRenderPipeline));
  63039. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63040. })(BABYLON || (BABYLON = {}));
  63041. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63042. var BABYLON;
  63043. (function (BABYLON) {
  63044. var FxaaPostProcess = /** @class */ (function (_super) {
  63045. __extends(FxaaPostProcess, _super);
  63046. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63047. if (camera === void 0) { camera = null; }
  63048. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63049. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63050. _this.onApplyObservable.add(function (effect) {
  63051. var texelSize = _this.texelSize;
  63052. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63053. });
  63054. return _this;
  63055. }
  63056. return FxaaPostProcess;
  63057. }(BABYLON.PostProcess));
  63058. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63059. })(BABYLON || (BABYLON = {}));
  63060. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63061. var BABYLON;
  63062. (function (BABYLON) {
  63063. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63064. __extends(DefaultRenderingPipeline, _super);
  63065. /**
  63066. * @constructor
  63067. * @param {string} name - The rendering pipeline name
  63068. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63069. * @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)
  63070. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63071. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63072. */
  63073. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63074. if (automaticBuild === void 0) { automaticBuild = true; }
  63075. var _this = _super.call(this, scene.getEngine(), name) || this;
  63076. _this.PassPostProcessId = "PassPostProcessEffect";
  63077. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63078. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63079. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63080. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63081. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63082. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63083. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63084. // IAnimatable
  63085. _this.animations = [];
  63086. // Values
  63087. _this._bloomEnabled = false;
  63088. _this._fxaaEnabled = false;
  63089. _this._imageProcessingEnabled = true;
  63090. _this._bloomScale = 0.6;
  63091. _this._buildAllowed = true;
  63092. /**
  63093. * Specifies the size of the bloom blur kernel, relative to the final output size
  63094. */
  63095. _this.bloomKernel = 64;
  63096. /**
  63097. * Specifies the weight of the bloom in the final rendering
  63098. */
  63099. _this._bloomWeight = 0.15;
  63100. _this._cameras = cameras || [];
  63101. _this._buildAllowed = automaticBuild;
  63102. // Initialize
  63103. _this._scene = scene;
  63104. var caps = _this._scene.getEngine().getCaps();
  63105. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63106. // Misc
  63107. if (_this._hdr) {
  63108. if (caps.textureHalfFloatRender) {
  63109. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63110. }
  63111. else if (caps.textureFloatRender) {
  63112. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63113. }
  63114. }
  63115. else {
  63116. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63117. }
  63118. // Attach
  63119. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63120. _this._buildPipeline();
  63121. return _this;
  63122. }
  63123. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63124. get: function () {
  63125. return this._bloomWeight;
  63126. },
  63127. set: function (value) {
  63128. if (this._bloomWeight === value) {
  63129. return;
  63130. }
  63131. this._bloomWeight = value;
  63132. if (this._hdr && this.copyBack) {
  63133. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63134. }
  63135. },
  63136. enumerable: true,
  63137. configurable: true
  63138. });
  63139. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63140. get: function () {
  63141. return this._bloomScale;
  63142. },
  63143. set: function (value) {
  63144. if (this._bloomScale === value) {
  63145. return;
  63146. }
  63147. this._bloomScale = value;
  63148. this._buildPipeline();
  63149. },
  63150. enumerable: true,
  63151. configurable: true
  63152. });
  63153. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63154. get: function () {
  63155. return this._bloomEnabled;
  63156. },
  63157. set: function (enabled) {
  63158. if (this._bloomEnabled === enabled) {
  63159. return;
  63160. }
  63161. this._bloomEnabled = enabled;
  63162. this._buildPipeline();
  63163. },
  63164. enumerable: true,
  63165. configurable: true
  63166. });
  63167. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63168. get: function () {
  63169. return this._fxaaEnabled;
  63170. },
  63171. set: function (enabled) {
  63172. if (this._fxaaEnabled === enabled) {
  63173. return;
  63174. }
  63175. this._fxaaEnabled = enabled;
  63176. this._buildPipeline();
  63177. },
  63178. enumerable: true,
  63179. configurable: true
  63180. });
  63181. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63182. get: function () {
  63183. return this._imageProcessingEnabled;
  63184. },
  63185. set: function (enabled) {
  63186. if (this._imageProcessingEnabled === enabled) {
  63187. return;
  63188. }
  63189. this._imageProcessingEnabled = enabled;
  63190. this._buildPipeline();
  63191. },
  63192. enumerable: true,
  63193. configurable: true
  63194. });
  63195. /**
  63196. * Force the compilation of the entire pipeline.
  63197. */
  63198. DefaultRenderingPipeline.prototype.prepare = function () {
  63199. var previousState = this._buildAllowed;
  63200. this._buildAllowed = true;
  63201. this._buildPipeline();
  63202. this._buildAllowed = previousState;
  63203. };
  63204. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63205. var _this = this;
  63206. if (!this._buildAllowed) {
  63207. return;
  63208. }
  63209. var engine = this._scene.getEngine();
  63210. this._disposePostProcesses();
  63211. this._reset();
  63212. if (this.bloomEnabled) {
  63213. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63214. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63215. if (!this._hdr) {
  63216. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63217. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63218. this.highlights.autoClear = false;
  63219. this.highlights.alwaysForcePOT = true;
  63220. }
  63221. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63222. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63223. this.blurX.alwaysForcePOT = true;
  63224. this.blurX.autoClear = false;
  63225. this.blurX.onActivateObservable.add(function () {
  63226. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63227. _this.blurX.kernel = _this.bloomKernel * dw;
  63228. });
  63229. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63230. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63231. this.blurY.alwaysForcePOT = true;
  63232. this.blurY.autoClear = false;
  63233. this.blurY.onActivateObservable.add(function () {
  63234. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63235. _this.blurY.kernel = _this.bloomKernel * dh;
  63236. });
  63237. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63238. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63239. this.copyBack.alwaysForcePOT = true;
  63240. if (this._hdr) {
  63241. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63242. var w = this.bloomWeight;
  63243. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63244. }
  63245. else {
  63246. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63247. }
  63248. this.copyBack.autoClear = false;
  63249. }
  63250. if (this._imageProcessingEnabled) {
  63251. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63252. if (this._hdr) {
  63253. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63254. }
  63255. else {
  63256. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63257. }
  63258. }
  63259. if (this.fxaaEnabled) {
  63260. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63261. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63262. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63263. }
  63264. else if (this._hdr && this.imageProcessing) {
  63265. this.finalMerge = this.imageProcessing;
  63266. }
  63267. else {
  63268. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63269. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63270. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63271. }
  63272. if (this.bloomEnabled) {
  63273. if (this._hdr) {
  63274. this.copyBack.shareOutputWith(this.blurX);
  63275. if (this.imageProcessing) {
  63276. this.imageProcessing.shareOutputWith(this.pass);
  63277. this.imageProcessing.autoClear = false;
  63278. }
  63279. else if (this.fxaa) {
  63280. this.fxaa.shareOutputWith(this.pass);
  63281. }
  63282. else {
  63283. this.finalMerge.shareOutputWith(this.pass);
  63284. }
  63285. }
  63286. else {
  63287. if (this.fxaa) {
  63288. this.fxaa.shareOutputWith(this.pass);
  63289. }
  63290. else {
  63291. this.finalMerge.shareOutputWith(this.pass);
  63292. }
  63293. }
  63294. }
  63295. if (this._cameras !== null) {
  63296. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63297. }
  63298. };
  63299. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63300. for (var i = 0; i < this._cameras.length; i++) {
  63301. var camera = this._cameras[i];
  63302. if (this.pass) {
  63303. this.pass.dispose(camera);
  63304. }
  63305. if (this.highlights) {
  63306. this.highlights.dispose(camera);
  63307. }
  63308. if (this.blurX) {
  63309. this.blurX.dispose(camera);
  63310. }
  63311. if (this.blurY) {
  63312. this.blurY.dispose(camera);
  63313. }
  63314. if (this.copyBack) {
  63315. this.copyBack.dispose(camera);
  63316. }
  63317. if (this.imageProcessing) {
  63318. this.imageProcessing.dispose(camera);
  63319. }
  63320. if (this.fxaa) {
  63321. this.fxaa.dispose(camera);
  63322. }
  63323. if (this.finalMerge) {
  63324. this.finalMerge.dispose(camera);
  63325. }
  63326. }
  63327. this.pass = null;
  63328. this.highlights = null;
  63329. this.blurX = null;
  63330. this.blurY = null;
  63331. this.copyBack = null;
  63332. this.imageProcessing = null;
  63333. this.fxaa = null;
  63334. this.finalMerge = null;
  63335. };
  63336. // Dispose
  63337. DefaultRenderingPipeline.prototype.dispose = function () {
  63338. this._disposePostProcesses();
  63339. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63340. _super.prototype.dispose.call(this);
  63341. };
  63342. // Serialize rendering pipeline
  63343. DefaultRenderingPipeline.prototype.serialize = function () {
  63344. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63345. serializationObject.customType = "DefaultRenderingPipeline";
  63346. return serializationObject;
  63347. };
  63348. // Parse serialized pipeline
  63349. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63350. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63351. };
  63352. __decorate([
  63353. BABYLON.serialize()
  63354. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63355. __decorate([
  63356. BABYLON.serialize()
  63357. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63358. __decorate([
  63359. BABYLON.serialize()
  63360. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63361. __decorate([
  63362. BABYLON.serialize()
  63363. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63364. __decorate([
  63365. BABYLON.serialize()
  63366. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63367. __decorate([
  63368. BABYLON.serialize()
  63369. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63370. __decorate([
  63371. BABYLON.serialize()
  63372. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63373. __decorate([
  63374. BABYLON.serialize()
  63375. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63376. return DefaultRenderingPipeline;
  63377. }(BABYLON.PostProcessRenderPipeline));
  63378. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63379. })(BABYLON || (BABYLON = {}));
  63380. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63381. var BABYLON;
  63382. (function (BABYLON) {
  63383. /**
  63384. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63385. */
  63386. var GeometryBufferRenderer = /** @class */ (function () {
  63387. /**
  63388. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63389. * @param scene The scene the buffer belongs to
  63390. * @param ratio How big is the buffer related to the main canvas.
  63391. */
  63392. function GeometryBufferRenderer(scene, ratio) {
  63393. if (ratio === void 0) { ratio = 1; }
  63394. this._enablePosition = false;
  63395. this._scene = scene;
  63396. this._ratio = ratio;
  63397. // Render target
  63398. this._createRenderTargets();
  63399. }
  63400. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63401. /**
  63402. * Set the render list (meshes to be rendered) used in the G buffer.
  63403. */
  63404. set: function (meshes) {
  63405. this._multiRenderTarget.renderList = meshes;
  63406. },
  63407. enumerable: true,
  63408. configurable: true
  63409. });
  63410. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63411. /**
  63412. * Gets wether or not G buffer are supported by the running hardware.
  63413. * This requires draw buffer supports
  63414. */
  63415. get: function () {
  63416. return this._multiRenderTarget.isSupported;
  63417. },
  63418. enumerable: true,
  63419. configurable: true
  63420. });
  63421. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63422. /**
  63423. * Gets wether or not position are enabled for the G buffer.
  63424. */
  63425. get: function () {
  63426. return this._enablePosition;
  63427. },
  63428. /**
  63429. * Sets wether or not position are enabled for the G buffer.
  63430. */
  63431. set: function (enable) {
  63432. this._enablePosition = enable;
  63433. this.dispose();
  63434. this._createRenderTargets();
  63435. },
  63436. enumerable: true,
  63437. configurable: true
  63438. });
  63439. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63440. /**
  63441. * Gets the scene associated with the buffer.
  63442. */
  63443. get: function () {
  63444. return this._scene;
  63445. },
  63446. enumerable: true,
  63447. configurable: true
  63448. });
  63449. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63450. /**
  63451. * Gets the ratio used by the buffer during its creation.
  63452. * How big is the buffer related to the main canvas.
  63453. */
  63454. get: function () {
  63455. return this._ratio;
  63456. },
  63457. enumerable: true,
  63458. configurable: true
  63459. });
  63460. /**
  63461. * Checks wether everything is ready to render a submesh to the G buffer.
  63462. * @param subMesh the submesh to check readiness for
  63463. * @param useInstances is the mesh drawn using instance or not
  63464. * @returns true if ready otherwise false
  63465. */
  63466. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63467. var material = subMesh.getMaterial();
  63468. if (material && material.disableDepthWrite) {
  63469. return false;
  63470. }
  63471. var defines = [];
  63472. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63473. var mesh = subMesh.getMesh();
  63474. // Alpha test
  63475. if (material && material.needAlphaTesting()) {
  63476. defines.push("#define ALPHATEST");
  63477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63478. attribs.push(BABYLON.VertexBuffer.UVKind);
  63479. defines.push("#define UV1");
  63480. }
  63481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63482. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63483. defines.push("#define UV2");
  63484. }
  63485. }
  63486. // Buffers
  63487. if (this._enablePosition) {
  63488. defines.push("#define POSITION");
  63489. }
  63490. // Bones
  63491. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63494. if (mesh.numBoneInfluencers > 4) {
  63495. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63496. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63497. }
  63498. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63499. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63500. }
  63501. else {
  63502. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63503. }
  63504. // Instances
  63505. if (useInstances) {
  63506. defines.push("#define INSTANCES");
  63507. attribs.push("world0");
  63508. attribs.push("world1");
  63509. attribs.push("world2");
  63510. attribs.push("world3");
  63511. }
  63512. // Get correct effect
  63513. var join = defines.join("\n");
  63514. if (this._cachedDefines !== join) {
  63515. this._cachedDefines = join;
  63516. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  63517. }
  63518. return this._effect.isReady();
  63519. };
  63520. /**
  63521. * Gets the current underlying G Buffer.
  63522. * @returns the buffer
  63523. */
  63524. GeometryBufferRenderer.prototype.getGBuffer = function () {
  63525. return this._multiRenderTarget;
  63526. };
  63527. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  63528. /**
  63529. * Gets the number of samples used to render the buffer (anti aliasing).
  63530. */
  63531. get: function () {
  63532. return this._multiRenderTarget.samples;
  63533. },
  63534. /**
  63535. * Sets the number of samples used to render the buffer (anti aliasing).
  63536. */
  63537. set: function (value) {
  63538. this._multiRenderTarget.samples = value;
  63539. },
  63540. enumerable: true,
  63541. configurable: true
  63542. });
  63543. /**
  63544. * Disposes the renderer and frees up associated resources.
  63545. */
  63546. GeometryBufferRenderer.prototype.dispose = function () {
  63547. this.getGBuffer().dispose();
  63548. };
  63549. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  63550. var _this = this;
  63551. var engine = this._scene.getEngine();
  63552. var count = this._enablePosition ? 3 : 2;
  63553. 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 });
  63554. if (!this.isSupported) {
  63555. return;
  63556. }
  63557. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63558. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63559. this._multiRenderTarget.refreshRate = 1;
  63560. this._multiRenderTarget.renderParticles = false;
  63561. this._multiRenderTarget.renderList = null;
  63562. // set default depth value to 1.0 (far away)
  63563. this._multiRenderTarget.onClearObservable.add(function (engine) {
  63564. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  63565. });
  63566. // Custom render function
  63567. var renderSubMesh = function (subMesh) {
  63568. var mesh = subMesh.getRenderingMesh();
  63569. var scene = _this._scene;
  63570. var engine = scene.getEngine();
  63571. var material = subMesh.getMaterial();
  63572. if (!material) {
  63573. return;
  63574. }
  63575. // Culling
  63576. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  63577. // Managing instances
  63578. var batch = mesh._getInstancesRenderList(subMesh._id);
  63579. if (batch.mustReturn) {
  63580. return;
  63581. }
  63582. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63583. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  63584. engine.enableEffect(_this._effect);
  63585. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  63586. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63587. _this._effect.setMatrix("view", scene.getViewMatrix());
  63588. // Alpha test
  63589. if (material && material.needAlphaTesting()) {
  63590. var alphaTexture = material.getAlphaTestTexture();
  63591. if (alphaTexture) {
  63592. _this._effect.setTexture("diffuseSampler", alphaTexture);
  63593. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63594. }
  63595. }
  63596. // Bones
  63597. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63598. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63599. }
  63600. // Draw
  63601. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63602. }
  63603. };
  63604. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63605. var index;
  63606. if (depthOnlySubMeshes.length) {
  63607. engine.setColorWrite(false);
  63608. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63609. renderSubMesh(depthOnlySubMeshes.data[index]);
  63610. }
  63611. engine.setColorWrite(true);
  63612. }
  63613. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63614. renderSubMesh(opaqueSubMeshes.data[index]);
  63615. }
  63616. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63617. renderSubMesh(alphaTestSubMeshes.data[index]);
  63618. }
  63619. };
  63620. };
  63621. return GeometryBufferRenderer;
  63622. }());
  63623. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  63624. })(BABYLON || (BABYLON = {}));
  63625. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  63626. var BABYLON;
  63627. (function (BABYLON) {
  63628. var RefractionPostProcess = /** @class */ (function (_super) {
  63629. __extends(RefractionPostProcess, _super);
  63630. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  63631. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  63632. _this.color = color;
  63633. _this.depth = depth;
  63634. _this.colorLevel = colorLevel;
  63635. _this.onActivateObservable.add(function (cam) {
  63636. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  63637. });
  63638. _this.onApplyObservable.add(function (effect) {
  63639. effect.setColor3("baseColor", _this.color);
  63640. effect.setFloat("depth", _this.depth);
  63641. effect.setFloat("colorLevel", _this.colorLevel);
  63642. effect.setTexture("refractionSampler", _this._refRexture);
  63643. });
  63644. return _this;
  63645. }
  63646. // Methods
  63647. RefractionPostProcess.prototype.dispose = function (camera) {
  63648. if (this._refRexture) {
  63649. this._refRexture.dispose();
  63650. }
  63651. _super.prototype.dispose.call(this, camera);
  63652. };
  63653. return RefractionPostProcess;
  63654. }(BABYLON.PostProcess));
  63655. BABYLON.RefractionPostProcess = RefractionPostProcess;
  63656. })(BABYLON || (BABYLON = {}));
  63657. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  63658. var BABYLON;
  63659. (function (BABYLON) {
  63660. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  63661. __extends(BlackAndWhitePostProcess, _super);
  63662. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  63663. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  63664. _this.degree = 1;
  63665. _this.onApplyObservable.add(function (effect) {
  63666. effect.setFloat("degree", _this.degree);
  63667. });
  63668. return _this;
  63669. }
  63670. return BlackAndWhitePostProcess;
  63671. }(BABYLON.PostProcess));
  63672. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  63673. })(BABYLON || (BABYLON = {}));
  63674. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  63675. var BABYLON;
  63676. (function (BABYLON) {
  63677. var ConvolutionPostProcess = /** @class */ (function (_super) {
  63678. __extends(ConvolutionPostProcess, _super);
  63679. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  63680. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  63681. _this.kernel = kernel;
  63682. _this.onApply = function (effect) {
  63683. effect.setFloat2("screenSize", _this.width, _this.height);
  63684. effect.setArray("kernel", _this.kernel);
  63685. };
  63686. return _this;
  63687. }
  63688. // Statics
  63689. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  63690. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  63691. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  63692. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  63693. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  63694. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  63695. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  63696. return ConvolutionPostProcess;
  63697. }(BABYLON.PostProcess));
  63698. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  63699. })(BABYLON || (BABYLON = {}));
  63700. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  63701. var BABYLON;
  63702. (function (BABYLON) {
  63703. var FilterPostProcess = /** @class */ (function (_super) {
  63704. __extends(FilterPostProcess, _super);
  63705. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  63706. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  63707. _this.kernelMatrix = kernelMatrix;
  63708. _this.onApply = function (effect) {
  63709. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  63710. };
  63711. return _this;
  63712. }
  63713. return FilterPostProcess;
  63714. }(BABYLON.PostProcess));
  63715. BABYLON.FilterPostProcess = FilterPostProcess;
  63716. })(BABYLON || (BABYLON = {}));
  63717. //# sourceMappingURL=babylon.filterPostProcess.js.map
  63718. var BABYLON;
  63719. (function (BABYLON) {
  63720. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  63721. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  63722. __extends(VolumetricLightScatteringPostProcess, _super);
  63723. /**
  63724. * @constructor
  63725. * @param {string} name - The post-process name
  63726. * @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)
  63727. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  63728. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  63729. * @param {number} samples - The post-process quality, default 100
  63730. * @param {number} samplingMode - The post-process filtering mode
  63731. * @param {BABYLON.Engine} engine - The babylon engine
  63732. * @param {boolean} reusable - If the post-process is reusable
  63733. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  63734. */
  63735. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  63736. if (samples === void 0) { samples = 100; }
  63737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63738. 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;
  63739. _this._screenCoordinates = BABYLON.Vector2.Zero();
  63740. /**
  63741. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  63742. * @type {Vector3}
  63743. */
  63744. _this.customMeshPosition = BABYLON.Vector3.Zero();
  63745. /**
  63746. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  63747. * @type {boolean}
  63748. */
  63749. _this.useCustomMeshPosition = false;
  63750. /**
  63751. * If the post-process should inverse the light scattering direction
  63752. * @type {boolean}
  63753. */
  63754. _this.invert = true;
  63755. /**
  63756. * Array containing the excluded meshes not rendered in the internal pass
  63757. */
  63758. _this.excludedMeshes = new Array();
  63759. /**
  63760. * Controls the overall intensity of the post-process
  63761. * @type {number}
  63762. */
  63763. _this.exposure = 0.3;
  63764. /**
  63765. * Dissipates each sample's contribution in range [0, 1]
  63766. * @type {number}
  63767. */
  63768. _this.decay = 0.96815;
  63769. /**
  63770. * Controls the overall intensity of each sample
  63771. * @type {number}
  63772. */
  63773. _this.weight = 0.58767;
  63774. /**
  63775. * Controls the density of each sample
  63776. * @type {number}
  63777. */
  63778. _this.density = 0.926;
  63779. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  63780. engine = scene.getEngine();
  63781. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  63782. // Configure mesh
  63783. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  63784. // Configure
  63785. _this._createPass(scene, ratio.passRatio || ratio);
  63786. _this.onActivate = function (camera) {
  63787. if (!_this.isSupported) {
  63788. _this.dispose(camera);
  63789. }
  63790. _this.onActivate = null;
  63791. };
  63792. _this.onApplyObservable.add(function (effect) {
  63793. _this._updateMeshScreenCoordinates(scene);
  63794. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  63795. effect.setFloat("exposure", _this.exposure);
  63796. effect.setFloat("decay", _this.decay);
  63797. effect.setFloat("weight", _this.weight);
  63798. effect.setFloat("density", _this.density);
  63799. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  63800. });
  63801. return _this;
  63802. }
  63803. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  63804. get: function () {
  63805. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63806. return false;
  63807. },
  63808. set: function (useDiffuseColor) {
  63809. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  63815. return "VolumetricLightScatteringPostProcess";
  63816. };
  63817. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  63818. var mesh = subMesh.getMesh();
  63819. // Render this.mesh as default
  63820. if (mesh === this.mesh && mesh.material) {
  63821. return mesh.material.isReady(mesh);
  63822. }
  63823. var defines = [];
  63824. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63825. var material = subMesh.getMaterial();
  63826. // Alpha test
  63827. if (material) {
  63828. if (material.needAlphaTesting()) {
  63829. defines.push("#define ALPHATEST");
  63830. }
  63831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63832. attribs.push(BABYLON.VertexBuffer.UVKind);
  63833. defines.push("#define UV1");
  63834. }
  63835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63836. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63837. defines.push("#define UV2");
  63838. }
  63839. }
  63840. // Bones
  63841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63844. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63845. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  63846. }
  63847. else {
  63848. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63849. }
  63850. // Instances
  63851. if (useInstances) {
  63852. defines.push("#define INSTANCES");
  63853. attribs.push("world0");
  63854. attribs.push("world1");
  63855. attribs.push("world2");
  63856. attribs.push("world3");
  63857. }
  63858. // Get correct effect
  63859. var join = defines.join("\n");
  63860. if (this._cachedDefines !== join) {
  63861. this._cachedDefines = join;
  63862. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  63863. }
  63864. return this._volumetricLightScatteringPass.isReady();
  63865. };
  63866. /**
  63867. * Sets the new light position for light scattering effect
  63868. * @param {BABYLON.Vector3} The new custom light position
  63869. */
  63870. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  63871. this.customMeshPosition = position;
  63872. };
  63873. /**
  63874. * Returns the light position for light scattering effect
  63875. * @return {BABYLON.Vector3} The custom light position
  63876. */
  63877. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  63878. return this.customMeshPosition;
  63879. };
  63880. /**
  63881. * Disposes the internal assets and detaches the post-process from the camera
  63882. */
  63883. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  63884. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  63885. if (rttIndex !== -1) {
  63886. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  63887. }
  63888. this._volumetricLightScatteringRTT.dispose();
  63889. _super.prototype.dispose.call(this, camera);
  63890. };
  63891. /**
  63892. * Returns the render target texture used by the post-process
  63893. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  63894. */
  63895. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  63896. return this._volumetricLightScatteringRTT;
  63897. };
  63898. // Private methods
  63899. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  63900. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  63901. return true;
  63902. }
  63903. return false;
  63904. };
  63905. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  63906. var _this = this;
  63907. var engine = scene.getEngine();
  63908. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63909. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63910. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63911. this._volumetricLightScatteringRTT.renderList = null;
  63912. this._volumetricLightScatteringRTT.renderParticles = false;
  63913. var camera = this.getCamera();
  63914. if (camera) {
  63915. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  63916. }
  63917. else {
  63918. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  63919. }
  63920. // Custom render function for submeshes
  63921. var renderSubMesh = function (subMesh) {
  63922. var mesh = subMesh.getRenderingMesh();
  63923. if (_this._meshExcluded(mesh)) {
  63924. return;
  63925. }
  63926. var material = subMesh.getMaterial();
  63927. if (!material) {
  63928. return;
  63929. }
  63930. var scene = mesh.getScene();
  63931. var engine = scene.getEngine();
  63932. // Culling
  63933. engine.setState(material.backFaceCulling);
  63934. // Managing instances
  63935. var batch = mesh._getInstancesRenderList(subMesh._id);
  63936. if (batch.mustReturn) {
  63937. return;
  63938. }
  63939. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63940. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  63941. var effect = _this._volumetricLightScatteringPass;
  63942. if (mesh === _this.mesh) {
  63943. if (subMesh.effect) {
  63944. effect = subMesh.effect;
  63945. }
  63946. else {
  63947. effect = material.getEffect();
  63948. }
  63949. }
  63950. engine.enableEffect(effect);
  63951. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  63952. if (mesh === _this.mesh) {
  63953. material.bind(mesh.getWorldMatrix(), mesh);
  63954. }
  63955. else {
  63956. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  63957. // Alpha test
  63958. if (material && material.needAlphaTesting()) {
  63959. var alphaTexture = material.getAlphaTestTexture();
  63960. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  63961. if (alphaTexture) {
  63962. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63963. }
  63964. }
  63965. // Bones
  63966. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63967. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63968. }
  63969. }
  63970. // Draw
  63971. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  63972. }
  63973. };
  63974. // Render target texture callbacks
  63975. var savedSceneClearColor;
  63976. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  63977. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  63978. savedSceneClearColor = scene.clearColor;
  63979. scene.clearColor = sceneClearColor;
  63980. });
  63981. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  63982. scene.clearColor = savedSceneClearColor;
  63983. });
  63984. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63985. var engine = scene.getEngine();
  63986. var index;
  63987. if (depthOnlySubMeshes.length) {
  63988. engine.setColorWrite(false);
  63989. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63990. renderSubMesh(depthOnlySubMeshes.data[index]);
  63991. }
  63992. engine.setColorWrite(true);
  63993. }
  63994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63995. renderSubMesh(opaqueSubMeshes.data[index]);
  63996. }
  63997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63998. renderSubMesh(alphaTestSubMeshes.data[index]);
  63999. }
  64000. if (transparentSubMeshes.length) {
  64001. // Sort sub meshes
  64002. for (index = 0; index < transparentSubMeshes.length; index++) {
  64003. var submesh = transparentSubMeshes.data[index];
  64004. var boundingInfo = submesh.getBoundingInfo();
  64005. if (boundingInfo && scene.activeCamera) {
  64006. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64007. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64008. }
  64009. }
  64010. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64011. sortedArray.sort(function (a, b) {
  64012. // Alpha index first
  64013. if (a._alphaIndex > b._alphaIndex) {
  64014. return 1;
  64015. }
  64016. if (a._alphaIndex < b._alphaIndex) {
  64017. return -1;
  64018. }
  64019. // Then distance to camera
  64020. if (a._distanceToCamera < b._distanceToCamera) {
  64021. return 1;
  64022. }
  64023. if (a._distanceToCamera > b._distanceToCamera) {
  64024. return -1;
  64025. }
  64026. return 0;
  64027. });
  64028. // Render sub meshes
  64029. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64030. for (index = 0; index < sortedArray.length; index++) {
  64031. renderSubMesh(sortedArray[index]);
  64032. }
  64033. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64034. }
  64035. };
  64036. };
  64037. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64038. var transform = scene.getTransformMatrix();
  64039. var meshPosition;
  64040. if (this.useCustomMeshPosition) {
  64041. meshPosition = this.customMeshPosition;
  64042. }
  64043. else if (this.attachedNode) {
  64044. meshPosition = this.attachedNode.position;
  64045. }
  64046. else {
  64047. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64048. }
  64049. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64050. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64051. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64052. if (this.invert)
  64053. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64054. };
  64055. // Static methods
  64056. /**
  64057. * Creates a default mesh for the Volumeric Light Scattering post-process
  64058. * @param {string} The mesh name
  64059. * @param {BABYLON.Scene} The scene where to create the mesh
  64060. * @return {BABYLON.Mesh} the default mesh
  64061. */
  64062. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64063. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64064. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64065. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64066. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64067. mesh.material = material;
  64068. return mesh;
  64069. };
  64070. __decorate([
  64071. BABYLON.serializeAsVector3()
  64072. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64073. __decorate([
  64074. BABYLON.serialize()
  64075. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64076. __decorate([
  64077. BABYLON.serialize()
  64078. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64079. __decorate([
  64080. BABYLON.serializeAsMeshReference()
  64081. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64082. __decorate([
  64083. BABYLON.serialize()
  64084. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64085. __decorate([
  64086. BABYLON.serialize()
  64087. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64088. __decorate([
  64089. BABYLON.serialize()
  64090. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64091. __decorate([
  64092. BABYLON.serialize()
  64093. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64094. __decorate([
  64095. BABYLON.serialize()
  64096. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64097. return VolumetricLightScatteringPostProcess;
  64098. }(BABYLON.PostProcess));
  64099. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64100. })(BABYLON || (BABYLON = {}));
  64101. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64102. //
  64103. // This post-process allows the modification of rendered colors by using
  64104. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64105. //
  64106. // The object needs to be provided an url to a texture containing the color
  64107. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64108. // Use an image editing software to tweak the LUT to match your needs.
  64109. //
  64110. // For an example of a color LUT, see here:
  64111. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64112. // For explanations on color grading, see here:
  64113. // http://udn.epicgames.com/Three/ColorGrading.html
  64114. //
  64115. var BABYLON;
  64116. (function (BABYLON) {
  64117. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64118. __extends(ColorCorrectionPostProcess, _super);
  64119. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64120. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64121. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64122. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64123. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64124. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64125. _this.onApply = function (effect) {
  64126. effect.setTexture("colorTable", _this._colorTableTexture);
  64127. };
  64128. return _this;
  64129. }
  64130. return ColorCorrectionPostProcess;
  64131. }(BABYLON.PostProcess));
  64132. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64133. })(BABYLON || (BABYLON = {}));
  64134. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64135. var BABYLON;
  64136. (function (BABYLON) {
  64137. var TonemappingOperator;
  64138. (function (TonemappingOperator) {
  64139. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64140. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64141. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64142. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64143. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64144. ;
  64145. var TonemapPostProcess = /** @class */ (function (_super) {
  64146. __extends(TonemapPostProcess, _super);
  64147. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64149. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64150. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64151. _this._operator = _operator;
  64152. _this.exposureAdjustment = exposureAdjustment;
  64153. var defines = "#define ";
  64154. if (_this._operator === TonemappingOperator.Hable)
  64155. defines += "HABLE_TONEMAPPING";
  64156. else if (_this._operator === TonemappingOperator.Reinhard)
  64157. defines += "REINHARD_TONEMAPPING";
  64158. else if (_this._operator === TonemappingOperator.HejiDawson)
  64159. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64160. else if (_this._operator === TonemappingOperator.Photographic)
  64161. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64162. //sadly a second call to create the effect.
  64163. _this.updateEffect(defines);
  64164. _this.onApply = function (effect) {
  64165. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64166. };
  64167. return _this;
  64168. }
  64169. return TonemapPostProcess;
  64170. }(BABYLON.PostProcess));
  64171. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64172. })(BABYLON || (BABYLON = {}));
  64173. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64174. var BABYLON;
  64175. (function (BABYLON) {
  64176. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64177. __extends(DisplayPassPostProcess, _super);
  64178. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64179. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64180. }
  64181. return DisplayPassPostProcess;
  64182. }(BABYLON.PostProcess));
  64183. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64184. })(BABYLON || (BABYLON = {}));
  64185. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64186. var BABYLON;
  64187. (function (BABYLON) {
  64188. var HighlightsPostProcess = /** @class */ (function (_super) {
  64189. __extends(HighlightsPostProcess, _super);
  64190. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64191. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64192. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64193. }
  64194. return HighlightsPostProcess;
  64195. }(BABYLON.PostProcess));
  64196. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64197. })(BABYLON || (BABYLON = {}));
  64198. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64199. var BABYLON;
  64200. (function (BABYLON) {
  64201. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64202. __extends(ImageProcessingPostProcess, _super);
  64203. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64204. if (camera === void 0) { camera = null; }
  64205. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64206. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64207. _this._fromLinearSpace = true;
  64208. /**
  64209. * Defines cache preventing GC.
  64210. */
  64211. _this._defines = {
  64212. IMAGEPROCESSING: false,
  64213. VIGNETTE: false,
  64214. VIGNETTEBLENDMODEMULTIPLY: false,
  64215. VIGNETTEBLENDMODEOPAQUE: false,
  64216. TONEMAPPING: false,
  64217. CONTRAST: false,
  64218. COLORCURVES: false,
  64219. COLORGRADING: false,
  64220. COLORGRADING3D: false,
  64221. FROMLINEARSPACE: false,
  64222. SAMPLER3DGREENDEPTH: false,
  64223. SAMPLER3DBGRMAP: false,
  64224. IMAGEPROCESSINGPOSTPROCESS: false,
  64225. EXPOSURE: false,
  64226. };
  64227. // Setup the configuration as forced by the constructor. This would then not force the
  64228. // scene materials output in linear space and let untouched the default forward pass.
  64229. if (imageProcessingConfiguration) {
  64230. imageProcessingConfiguration.applyByPostProcess = true;
  64231. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64232. // This will cause the shader to be compiled
  64233. _this.fromLinearSpace = false;
  64234. }
  64235. else {
  64236. _this._attachImageProcessingConfiguration(null, true);
  64237. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64238. }
  64239. _this.onApply = function (effect) {
  64240. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64241. };
  64242. return _this;
  64243. }
  64244. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64245. /**
  64246. * Gets the image processing configuration used either in this material.
  64247. */
  64248. get: function () {
  64249. return this._imageProcessingConfiguration;
  64250. },
  64251. /**
  64252. * Sets the Default image processing configuration used either in the this material.
  64253. *
  64254. * If sets to null, the scene one is in use.
  64255. */
  64256. set: function (value) {
  64257. this._attachImageProcessingConfiguration(value);
  64258. },
  64259. enumerable: true,
  64260. configurable: true
  64261. });
  64262. /**
  64263. * Attaches a new image processing configuration to the PBR Material.
  64264. * @param configuration
  64265. */
  64266. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64267. var _this = this;
  64268. if (doNotBuild === void 0) { doNotBuild = false; }
  64269. if (configuration === this._imageProcessingConfiguration) {
  64270. return;
  64271. }
  64272. // Detaches observer.
  64273. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64274. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64275. }
  64276. // Pick the scene configuration if needed.
  64277. if (!configuration) {
  64278. var scene = null;
  64279. var engine = this.getEngine();
  64280. var camera = this.getCamera();
  64281. if (camera) {
  64282. scene = camera.getScene();
  64283. }
  64284. else if (engine && engine.scenes) {
  64285. var scenes = engine.scenes;
  64286. scene = scenes[scenes.length - 1];
  64287. }
  64288. else {
  64289. scene = BABYLON.Engine.LastCreatedScene;
  64290. }
  64291. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64292. }
  64293. else {
  64294. this._imageProcessingConfiguration = configuration;
  64295. }
  64296. // Attaches observer.
  64297. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64298. _this._updateParameters();
  64299. });
  64300. // Ensure the effect will be rebuilt.
  64301. if (!doNotBuild) {
  64302. this._updateParameters();
  64303. }
  64304. };
  64305. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64306. /**
  64307. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64308. */
  64309. get: function () {
  64310. return this.imageProcessingConfiguration.colorCurves;
  64311. },
  64312. /**
  64313. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64314. */
  64315. set: function (value) {
  64316. this.imageProcessingConfiguration.colorCurves = value;
  64317. },
  64318. enumerable: true,
  64319. configurable: true
  64320. });
  64321. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64322. /**
  64323. * Gets wether the color curves effect is enabled.
  64324. */
  64325. get: function () {
  64326. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64327. },
  64328. /**
  64329. * Sets wether the color curves effect is enabled.
  64330. */
  64331. set: function (value) {
  64332. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64333. },
  64334. enumerable: true,
  64335. configurable: true
  64336. });
  64337. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64338. /**
  64339. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64340. */
  64341. get: function () {
  64342. return this.imageProcessingConfiguration.colorGradingTexture;
  64343. },
  64344. /**
  64345. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64346. */
  64347. set: function (value) {
  64348. this.imageProcessingConfiguration.colorGradingTexture = value;
  64349. },
  64350. enumerable: true,
  64351. configurable: true
  64352. });
  64353. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64354. /**
  64355. * Gets wether the color grading effect is enabled.
  64356. */
  64357. get: function () {
  64358. return this.imageProcessingConfiguration.colorGradingEnabled;
  64359. },
  64360. /**
  64361. * Gets wether the color grading effect is enabled.
  64362. */
  64363. set: function (value) {
  64364. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64365. },
  64366. enumerable: true,
  64367. configurable: true
  64368. });
  64369. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64370. /**
  64371. * Gets exposure used in the effect.
  64372. */
  64373. get: function () {
  64374. return this.imageProcessingConfiguration.exposure;
  64375. },
  64376. /**
  64377. * Sets exposure used in the effect.
  64378. */
  64379. set: function (value) {
  64380. this.imageProcessingConfiguration.exposure = value;
  64381. },
  64382. enumerable: true,
  64383. configurable: true
  64384. });
  64385. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64386. /**
  64387. * Gets wether tonemapping is enabled or not.
  64388. */
  64389. get: function () {
  64390. return this._imageProcessingConfiguration.toneMappingEnabled;
  64391. },
  64392. /**
  64393. * Sets wether tonemapping is enabled or not
  64394. */
  64395. set: function (value) {
  64396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64397. },
  64398. enumerable: true,
  64399. configurable: true
  64400. });
  64401. ;
  64402. ;
  64403. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64404. /**
  64405. * Gets contrast used in the effect.
  64406. */
  64407. get: function () {
  64408. return this.imageProcessingConfiguration.contrast;
  64409. },
  64410. /**
  64411. * Sets contrast used in the effect.
  64412. */
  64413. set: function (value) {
  64414. this.imageProcessingConfiguration.contrast = value;
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64420. /**
  64421. * Gets Vignette stretch size.
  64422. */
  64423. get: function () {
  64424. return this.imageProcessingConfiguration.vignetteStretch;
  64425. },
  64426. /**
  64427. * Sets Vignette stretch size.
  64428. */
  64429. set: function (value) {
  64430. this.imageProcessingConfiguration.vignetteStretch = value;
  64431. },
  64432. enumerable: true,
  64433. configurable: true
  64434. });
  64435. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64436. /**
  64437. * Gets Vignette centre X Offset.
  64438. */
  64439. get: function () {
  64440. return this.imageProcessingConfiguration.vignetteCentreX;
  64441. },
  64442. /**
  64443. * Sets Vignette centre X Offset.
  64444. */
  64445. set: function (value) {
  64446. this.imageProcessingConfiguration.vignetteCentreX = value;
  64447. },
  64448. enumerable: true,
  64449. configurable: true
  64450. });
  64451. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64452. /**
  64453. * Gets Vignette centre Y Offset.
  64454. */
  64455. get: function () {
  64456. return this.imageProcessingConfiguration.vignetteCentreY;
  64457. },
  64458. /**
  64459. * Sets Vignette centre Y Offset.
  64460. */
  64461. set: function (value) {
  64462. this.imageProcessingConfiguration.vignetteCentreY = value;
  64463. },
  64464. enumerable: true,
  64465. configurable: true
  64466. });
  64467. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  64468. /**
  64469. * Gets Vignette weight or intensity of the vignette effect.
  64470. */
  64471. get: function () {
  64472. return this.imageProcessingConfiguration.vignetteWeight;
  64473. },
  64474. /**
  64475. * Sets Vignette weight or intensity of the vignette effect.
  64476. */
  64477. set: function (value) {
  64478. this.imageProcessingConfiguration.vignetteWeight = value;
  64479. },
  64480. enumerable: true,
  64481. configurable: true
  64482. });
  64483. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  64484. /**
  64485. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64486. * if vignetteEnabled is set to true.
  64487. */
  64488. get: function () {
  64489. return this.imageProcessingConfiguration.vignetteColor;
  64490. },
  64491. /**
  64492. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64493. * if vignetteEnabled is set to true.
  64494. */
  64495. set: function (value) {
  64496. this.imageProcessingConfiguration.vignetteColor = value;
  64497. },
  64498. enumerable: true,
  64499. configurable: true
  64500. });
  64501. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  64502. /**
  64503. * Gets Camera field of view used by the Vignette effect.
  64504. */
  64505. get: function () {
  64506. return this.imageProcessingConfiguration.vignetteCameraFov;
  64507. },
  64508. /**
  64509. * Sets Camera field of view used by the Vignette effect.
  64510. */
  64511. set: function (value) {
  64512. this.imageProcessingConfiguration.vignetteCameraFov = value;
  64513. },
  64514. enumerable: true,
  64515. configurable: true
  64516. });
  64517. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  64518. /**
  64519. * Gets the vignette blend mode allowing different kind of effect.
  64520. */
  64521. get: function () {
  64522. return this.imageProcessingConfiguration.vignetteBlendMode;
  64523. },
  64524. /**
  64525. * Sets the vignette blend mode allowing different kind of effect.
  64526. */
  64527. set: function (value) {
  64528. this.imageProcessingConfiguration.vignetteBlendMode = value;
  64529. },
  64530. enumerable: true,
  64531. configurable: true
  64532. });
  64533. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  64534. /**
  64535. * Gets wether the vignette effect is enabled.
  64536. */
  64537. get: function () {
  64538. return this.imageProcessingConfiguration.vignetteEnabled;
  64539. },
  64540. /**
  64541. * Sets wether the vignette effect is enabled.
  64542. */
  64543. set: function (value) {
  64544. this.imageProcessingConfiguration.vignetteEnabled = value;
  64545. },
  64546. enumerable: true,
  64547. configurable: true
  64548. });
  64549. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  64550. /**
  64551. * Gets wether the input of the processing is in Gamma or Linear Space.
  64552. */
  64553. get: function () {
  64554. return this._fromLinearSpace;
  64555. },
  64556. /**
  64557. * Sets wether the input of the processing is in Gamma or Linear Space.
  64558. */
  64559. set: function (value) {
  64560. if (this._fromLinearSpace === value) {
  64561. return;
  64562. }
  64563. this._fromLinearSpace = value;
  64564. this._updateParameters();
  64565. },
  64566. enumerable: true,
  64567. configurable: true
  64568. });
  64569. ImageProcessingPostProcess.prototype.getClassName = function () {
  64570. return "ImageProcessingPostProcess";
  64571. };
  64572. ImageProcessingPostProcess.prototype._updateParameters = function () {
  64573. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  64574. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  64575. var defines = "";
  64576. for (var define in this._defines) {
  64577. if (this._defines[define]) {
  64578. defines += "#define " + define + ";\r\n";
  64579. }
  64580. }
  64581. var samplers = ["textureSampler"];
  64582. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  64583. var uniforms = ["scale"];
  64584. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  64585. this.updateEffect(defines, uniforms, samplers);
  64586. };
  64587. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  64588. _super.prototype.dispose.call(this, camera);
  64589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64591. }
  64592. this.imageProcessingConfiguration.applyByPostProcess = false;
  64593. };
  64594. __decorate([
  64595. BABYLON.serialize()
  64596. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  64597. return ImageProcessingPostProcess;
  64598. }(BABYLON.PostProcess));
  64599. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  64600. })(BABYLON || (BABYLON = {}));
  64601. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  64602. var BABYLON;
  64603. (function (BABYLON) {
  64604. var BlurPostProcess = /** @class */ (function (_super) {
  64605. __extends(BlurPostProcess, _super);
  64606. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  64607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64609. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  64610. _this.direction = direction;
  64611. _this._packedFloat = false;
  64612. _this.onApplyObservable.add(function (effect) {
  64613. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  64614. });
  64615. _this.kernel = kernel;
  64616. return _this;
  64617. }
  64618. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  64619. /**
  64620. * Gets the length in pixels of the blur sample region
  64621. */
  64622. get: function () {
  64623. return this._idealKernel;
  64624. },
  64625. /**
  64626. * Sets the length in pixels of the blur sample region
  64627. */
  64628. set: function (v) {
  64629. if (this._idealKernel === v) {
  64630. return;
  64631. }
  64632. v = Math.max(v, 1);
  64633. this._idealKernel = v;
  64634. this._kernel = this._nearestBestKernel(v);
  64635. this._updateParameters();
  64636. },
  64637. enumerable: true,
  64638. configurable: true
  64639. });
  64640. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  64641. /**
  64642. * Gets wether or not the blur is unpacking/repacking floats
  64643. */
  64644. get: function () {
  64645. return this._packedFloat;
  64646. },
  64647. /**
  64648. * Sets wether or not the blur needs to unpack/repack floats
  64649. */
  64650. set: function (v) {
  64651. if (this._packedFloat === v) {
  64652. return;
  64653. }
  64654. this._packedFloat = v;
  64655. this._updateParameters();
  64656. },
  64657. enumerable: true,
  64658. configurable: true
  64659. });
  64660. BlurPostProcess.prototype._updateParameters = function () {
  64661. // Generate sampling offsets and weights
  64662. var N = this._kernel;
  64663. var centerIndex = (N - 1) / 2;
  64664. // Generate Gaussian sampling weights over kernel
  64665. var offsets = [];
  64666. var weights = [];
  64667. var totalWeight = 0;
  64668. for (var i = 0; i < N; i++) {
  64669. var u = i / (N - 1);
  64670. var w = this._gaussianWeight(u * 2.0 - 1);
  64671. offsets[i] = (i - centerIndex);
  64672. weights[i] = w;
  64673. totalWeight += w;
  64674. }
  64675. // Normalize weights
  64676. for (var i = 0; i < weights.length; i++) {
  64677. weights[i] /= totalWeight;
  64678. }
  64679. // Optimize: combine samples to take advantage of hardware linear sampling
  64680. // Walk from left to center, combining pairs (symmetrically)
  64681. var linearSamplingWeights = [];
  64682. var linearSamplingOffsets = [];
  64683. var linearSamplingMap = [];
  64684. for (var i = 0; i <= centerIndex; i += 2) {
  64685. var j = Math.min(i + 1, Math.floor(centerIndex));
  64686. var singleCenterSample = i === j;
  64687. if (singleCenterSample) {
  64688. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64689. }
  64690. else {
  64691. var sharedCell = j === centerIndex;
  64692. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  64693. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  64694. if (offsetLinear === 0) {
  64695. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64696. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  64697. }
  64698. else {
  64699. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  64700. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  64701. }
  64702. }
  64703. }
  64704. for (var i = 0; i < linearSamplingMap.length; i++) {
  64705. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  64706. linearSamplingWeights[i] = linearSamplingMap[i].w;
  64707. }
  64708. // Replace with optimized
  64709. offsets = linearSamplingOffsets;
  64710. weights = linearSamplingWeights;
  64711. // Generate shaders
  64712. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  64713. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  64714. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  64715. var defines = "";
  64716. for (var i = 0; i < varyingCount; i++) {
  64717. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  64718. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  64719. }
  64720. var depCount = 0;
  64721. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  64722. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  64723. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  64724. depCount++;
  64725. }
  64726. if (this.packedFloat) {
  64727. defines += "#define PACKEDFLOAT 1";
  64728. }
  64729. this.updateEffect(defines, null, null, {
  64730. varyingCount: varyingCount,
  64731. depCount: depCount
  64732. });
  64733. };
  64734. /**
  64735. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  64736. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  64737. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  64738. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  64739. * The gaps between physical kernels are compensated for in the weighting of the samples
  64740. * @param idealKernel Ideal blur kernel.
  64741. * @return Nearest best kernel.
  64742. */
  64743. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  64744. var v = Math.round(idealKernel);
  64745. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  64746. var k = _a[_i];
  64747. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  64748. return Math.max(k, 3);
  64749. }
  64750. }
  64751. return Math.max(v, 3);
  64752. };
  64753. /**
  64754. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  64755. * @param x The point on the Gaussian distribution to sample.
  64756. * @return the value of the Gaussian function at x.
  64757. */
  64758. BlurPostProcess.prototype._gaussianWeight = function (x) {
  64759. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  64760. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  64761. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  64762. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  64763. // truncated at around 1.3% of peak strength.
  64764. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  64765. var sigma = (1 / 3);
  64766. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  64767. var exponent = -((x * x) / (2.0 * sigma * sigma));
  64768. var weight = (1.0 / denominator) * Math.exp(exponent);
  64769. return weight;
  64770. };
  64771. /**
  64772. * Generates a string that can be used as a floating point number in GLSL.
  64773. * @param x Value to print.
  64774. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  64775. * @return GLSL float string.
  64776. */
  64777. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  64778. if (decimalFigures === void 0) { decimalFigures = 8; }
  64779. return x.toFixed(decimalFigures).replace(/0+$/, '');
  64780. };
  64781. return BlurPostProcess;
  64782. }(BABYLON.PostProcess));
  64783. BABYLON.BlurPostProcess = BlurPostProcess;
  64784. })(BABYLON || (BABYLON = {}));
  64785. //# sourceMappingURL=babylon.blurPostProcess.js.map
  64786. var BABYLON;
  64787. (function (BABYLON) {
  64788. var Bone = /** @class */ (function (_super) {
  64789. __extends(Bone, _super);
  64790. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  64791. if (parentBone === void 0) { parentBone = null; }
  64792. if (localMatrix === void 0) { localMatrix = null; }
  64793. if (restPose === void 0) { restPose = null; }
  64794. if (baseMatrix === void 0) { baseMatrix = null; }
  64795. if (index === void 0) { index = null; }
  64796. var _this = _super.call(this, name, skeleton.getScene()) || this;
  64797. _this.name = name;
  64798. _this.children = new Array();
  64799. _this.animations = new Array();
  64800. // Set this value to map this bone to a different index in the transform matrices.
  64801. // Set this value to -1 to exclude the bone from the transform matrices.
  64802. _this._index = null;
  64803. _this._worldTransform = new BABYLON.Matrix();
  64804. _this._absoluteTransform = new BABYLON.Matrix();
  64805. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  64806. _this._scaleMatrix = BABYLON.Matrix.Identity();
  64807. _this._scaleVector = BABYLON.Vector3.One();
  64808. _this._negateScaleChildren = BABYLON.Vector3.One();
  64809. _this._scalingDeterminant = 1;
  64810. _this._skeleton = skeleton;
  64811. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  64812. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  64813. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  64814. _this._index = index;
  64815. skeleton.bones.push(_this);
  64816. _this.setParent(parentBone, false);
  64817. _this._updateDifferenceMatrix();
  64818. return _this;
  64819. }
  64820. Object.defineProperty(Bone.prototype, "_matrix", {
  64821. get: function () {
  64822. return this._localMatrix;
  64823. },
  64824. set: function (val) {
  64825. if (this._localMatrix) {
  64826. this._localMatrix.copyFrom(val);
  64827. }
  64828. else {
  64829. this._localMatrix = val;
  64830. }
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. // Members
  64836. Bone.prototype.getSkeleton = function () {
  64837. return this._skeleton;
  64838. };
  64839. Bone.prototype.getParent = function () {
  64840. return this._parent;
  64841. };
  64842. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  64843. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  64844. if (this._parent === parent) {
  64845. return;
  64846. }
  64847. if (this._parent) {
  64848. var index = this._parent.children.indexOf(this);
  64849. if (index !== -1) {
  64850. this._parent.children.splice(index, 1);
  64851. }
  64852. }
  64853. this._parent = parent;
  64854. if (this._parent) {
  64855. this._parent.children.push(this);
  64856. }
  64857. if (updateDifferenceMatrix) {
  64858. this._updateDifferenceMatrix();
  64859. }
  64860. };
  64861. Bone.prototype.getLocalMatrix = function () {
  64862. return this._localMatrix;
  64863. };
  64864. Bone.prototype.getBaseMatrix = function () {
  64865. return this._baseMatrix;
  64866. };
  64867. Bone.prototype.getRestPose = function () {
  64868. return this._restPose;
  64869. };
  64870. Bone.prototype.returnToRest = function () {
  64871. this.updateMatrix(this._restPose.clone());
  64872. };
  64873. Bone.prototype.getWorldMatrix = function () {
  64874. return this._worldTransform;
  64875. };
  64876. Bone.prototype.getInvertedAbsoluteTransform = function () {
  64877. return this._invertedAbsoluteTransform;
  64878. };
  64879. Bone.prototype.getAbsoluteTransform = function () {
  64880. return this._absoluteTransform;
  64881. };
  64882. Object.defineProperty(Bone.prototype, "position", {
  64883. // Properties (matches AbstractMesh properties)
  64884. get: function () {
  64885. return this.getPosition();
  64886. },
  64887. set: function (newPosition) {
  64888. this.setPosition(newPosition);
  64889. },
  64890. enumerable: true,
  64891. configurable: true
  64892. });
  64893. Object.defineProperty(Bone.prototype, "rotation", {
  64894. get: function () {
  64895. return this.getRotation();
  64896. },
  64897. set: function (newRotation) {
  64898. this.setRotation(newRotation);
  64899. },
  64900. enumerable: true,
  64901. configurable: true
  64902. });
  64903. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  64904. get: function () {
  64905. return this.getRotationQuaternion();
  64906. },
  64907. set: function (newRotation) {
  64908. this.setRotationQuaternion(newRotation);
  64909. },
  64910. enumerable: true,
  64911. configurable: true
  64912. });
  64913. Object.defineProperty(Bone.prototype, "scaling", {
  64914. get: function () {
  64915. return this.getScale();
  64916. },
  64917. set: function (newScaling) {
  64918. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  64919. },
  64920. enumerable: true,
  64921. configurable: true
  64922. });
  64923. // Methods
  64924. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  64925. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  64926. this._baseMatrix = matrix.clone();
  64927. this._localMatrix = matrix.clone();
  64928. this._skeleton._markAsDirty();
  64929. if (updateDifferenceMatrix) {
  64930. this._updateDifferenceMatrix();
  64931. }
  64932. };
  64933. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  64934. if (!rootMatrix) {
  64935. rootMatrix = this._baseMatrix;
  64936. }
  64937. if (this._parent) {
  64938. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  64939. }
  64940. else {
  64941. this._absoluteTransform.copyFrom(rootMatrix);
  64942. }
  64943. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  64944. for (var index = 0; index < this.children.length; index++) {
  64945. this.children[index]._updateDifferenceMatrix();
  64946. }
  64947. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  64948. };
  64949. Bone.prototype.markAsDirty = function () {
  64950. this._currentRenderId++;
  64951. this._skeleton._markAsDirty();
  64952. };
  64953. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  64954. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64955. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  64956. // all animation may be coming from a library skeleton, so may need to create animation
  64957. if (this.animations.length === 0) {
  64958. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  64959. this.animations[0].setKeys([]);
  64960. }
  64961. // get animation info / verify there is such a range from the source bone
  64962. var sourceRange = source.animations[0].getRange(rangeName);
  64963. if (!sourceRange) {
  64964. return false;
  64965. }
  64966. var from = sourceRange.from;
  64967. var to = sourceRange.to;
  64968. var sourceKeys = source.animations[0].getKeys();
  64969. // rescaling prep
  64970. var sourceBoneLength = source.length;
  64971. var sourceParent = source.getParent();
  64972. var parent = this.getParent();
  64973. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  64974. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  64975. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  64976. var destKeys = this.animations[0].getKeys();
  64977. // loop vars declaration
  64978. var orig;
  64979. var origTranslation;
  64980. var mat;
  64981. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  64982. orig = sourceKeys[key];
  64983. if (orig.frame >= from && orig.frame <= to) {
  64984. if (rescaleAsRequired) {
  64985. mat = orig.value.clone();
  64986. // scale based on parent ratio, when bone has parent
  64987. if (parentScalingReqd) {
  64988. origTranslation = mat.getTranslation();
  64989. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  64990. // scale based on skeleton dimension ratio when root bone, and value is passed
  64991. }
  64992. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  64993. origTranslation = mat.getTranslation();
  64994. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  64995. // use original when root bone, and no data for skelDimensionsRatio
  64996. }
  64997. else {
  64998. mat = orig.value;
  64999. }
  65000. }
  65001. else {
  65002. mat = orig.value;
  65003. }
  65004. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65005. }
  65006. }
  65007. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65008. return true;
  65009. };
  65010. /**
  65011. * Translate the bone in local or world space.
  65012. * @param vec The amount to translate the bone.
  65013. * @param space The space that the translation is in.
  65014. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65015. */
  65016. Bone.prototype.translate = function (vec, space, mesh) {
  65017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65018. var lm = this.getLocalMatrix();
  65019. if (space == BABYLON.Space.LOCAL) {
  65020. lm.m[12] += vec.x;
  65021. lm.m[13] += vec.y;
  65022. lm.m[14] += vec.z;
  65023. }
  65024. else {
  65025. var wm = null;
  65026. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65027. if (mesh) {
  65028. wm = mesh.getWorldMatrix();
  65029. }
  65030. this._skeleton.computeAbsoluteTransforms();
  65031. var tmat = Bone._tmpMats[0];
  65032. var tvec = Bone._tmpVecs[0];
  65033. if (this._parent) {
  65034. if (mesh && wm) {
  65035. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65036. tmat.multiplyToRef(wm, tmat);
  65037. }
  65038. else {
  65039. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65040. }
  65041. }
  65042. tmat.m[12] = 0;
  65043. tmat.m[13] = 0;
  65044. tmat.m[14] = 0;
  65045. tmat.invert();
  65046. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65047. lm.m[12] += tvec.x;
  65048. lm.m[13] += tvec.y;
  65049. lm.m[14] += tvec.z;
  65050. }
  65051. this.markAsDirty();
  65052. };
  65053. /**
  65054. * Set the postion of the bone in local or world space.
  65055. * @param position The position to set the bone.
  65056. * @param space The space that the position is in.
  65057. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65058. */
  65059. Bone.prototype.setPosition = function (position, space, mesh) {
  65060. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65061. var lm = this.getLocalMatrix();
  65062. if (space == BABYLON.Space.LOCAL) {
  65063. lm.m[12] = position.x;
  65064. lm.m[13] = position.y;
  65065. lm.m[14] = position.z;
  65066. }
  65067. else {
  65068. var wm = null;
  65069. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65070. if (mesh) {
  65071. wm = mesh.getWorldMatrix();
  65072. }
  65073. this._skeleton.computeAbsoluteTransforms();
  65074. var tmat = Bone._tmpMats[0];
  65075. var vec = Bone._tmpVecs[0];
  65076. if (this._parent) {
  65077. if (mesh && wm) {
  65078. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65079. tmat.multiplyToRef(wm, tmat);
  65080. }
  65081. else {
  65082. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65083. }
  65084. }
  65085. tmat.invert();
  65086. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65087. lm.m[12] = vec.x;
  65088. lm.m[13] = vec.y;
  65089. lm.m[14] = vec.z;
  65090. }
  65091. this.markAsDirty();
  65092. };
  65093. /**
  65094. * Set the absolute postion of the bone (world space).
  65095. * @param position The position to set the bone.
  65096. * @param mesh The mesh that this bone is attached to.
  65097. */
  65098. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65099. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65100. };
  65101. /**
  65102. * Set the scale of the bone on the x, y and z axes.
  65103. * @param x The scale of the bone on the x axis.
  65104. * @param x The scale of the bone on the y axis.
  65105. * @param z The scale of the bone on the z axis.
  65106. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65107. */
  65108. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65109. if (scaleChildren === void 0) { scaleChildren = false; }
  65110. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65111. if (!scaleChildren) {
  65112. this._negateScaleChildren.x = 1 / x;
  65113. this._negateScaleChildren.y = 1 / y;
  65114. this._negateScaleChildren.z = 1 / z;
  65115. }
  65116. this._syncScaleVector();
  65117. }
  65118. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65119. };
  65120. /**
  65121. * Scale the bone on the x, y and z axes.
  65122. * @param x The amount to scale the bone on the x axis.
  65123. * @param x The amount to scale the bone on the y axis.
  65124. * @param z The amount to scale the bone on the z axis.
  65125. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65126. */
  65127. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65128. if (scaleChildren === void 0) { scaleChildren = false; }
  65129. var locMat = this.getLocalMatrix();
  65130. var origLocMat = Bone._tmpMats[0];
  65131. origLocMat.copyFrom(locMat);
  65132. var origLocMatInv = Bone._tmpMats[1];
  65133. origLocMatInv.copyFrom(origLocMat);
  65134. origLocMatInv.invert();
  65135. var scaleMat = Bone._tmpMats[2];
  65136. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65137. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65138. this._scaleVector.x *= x;
  65139. this._scaleVector.y *= y;
  65140. this._scaleVector.z *= z;
  65141. locMat.multiplyToRef(origLocMatInv, locMat);
  65142. locMat.multiplyToRef(scaleMat, locMat);
  65143. locMat.multiplyToRef(origLocMat, locMat);
  65144. var parent = this.getParent();
  65145. if (parent) {
  65146. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65147. }
  65148. else {
  65149. this.getAbsoluteTransform().copyFrom(locMat);
  65150. }
  65151. var len = this.children.length;
  65152. scaleMat.invert();
  65153. for (var i = 0; i < len; i++) {
  65154. var child = this.children[i];
  65155. var cm = child.getLocalMatrix();
  65156. cm.multiplyToRef(scaleMat, cm);
  65157. var lm = child.getLocalMatrix();
  65158. lm.m[12] *= x;
  65159. lm.m[13] *= y;
  65160. lm.m[14] *= z;
  65161. }
  65162. this.computeAbsoluteTransforms();
  65163. if (scaleChildren) {
  65164. for (var i = 0; i < len; i++) {
  65165. this.children[i].scale(x, y, z, scaleChildren);
  65166. }
  65167. }
  65168. this.markAsDirty();
  65169. };
  65170. /**
  65171. * Set the yaw, pitch, and roll of the bone in local or world space.
  65172. * @param yaw The rotation of the bone on the y axis.
  65173. * @param pitch The rotation of the bone on the x axis.
  65174. * @param roll The rotation of the bone on the z axis.
  65175. * @param space The space that the axes of rotation are in.
  65176. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65177. */
  65178. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65180. var rotMat = Bone._tmpMats[0];
  65181. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65182. var rotMatInv = Bone._tmpMats[1];
  65183. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65184. rotMatInv.multiplyToRef(rotMat, rotMat);
  65185. this._rotateWithMatrix(rotMat, space, mesh);
  65186. };
  65187. /**
  65188. * Rotate the bone on an axis in local or world space.
  65189. * @param axis The axis to rotate the bone on.
  65190. * @param amount The amount to rotate the bone.
  65191. * @param space The space that the axis is in.
  65192. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65193. */
  65194. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65196. var rmat = Bone._tmpMats[0];
  65197. rmat.m[12] = 0;
  65198. rmat.m[13] = 0;
  65199. rmat.m[14] = 0;
  65200. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65201. this._rotateWithMatrix(rmat, space, mesh);
  65202. };
  65203. /**
  65204. * Set the rotation of the bone to a particular axis angle in local or world space.
  65205. * @param axis The axis to rotate the bone on.
  65206. * @param angle The angle that the bone should be rotated to.
  65207. * @param space The space that the axis is in.
  65208. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65209. */
  65210. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65211. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65212. var rotMat = Bone._tmpMats[0];
  65213. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65214. var rotMatInv = Bone._tmpMats[1];
  65215. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65216. rotMatInv.multiplyToRef(rotMat, rotMat);
  65217. this._rotateWithMatrix(rotMat, space, mesh);
  65218. };
  65219. /**
  65220. * Set the euler rotation of the bone in local of world space.
  65221. * @param rotation The euler rotation that the bone should be set to.
  65222. * @param space The space that the rotation is in.
  65223. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65224. */
  65225. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65226. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65227. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65228. };
  65229. /**
  65230. * Set the quaternion rotation of the bone in local of world space.
  65231. * @param quat The quaternion rotation that the bone should be set to.
  65232. * @param space The space that the rotation is in.
  65233. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65234. */
  65235. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65236. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65237. var rotMatInv = Bone._tmpMats[0];
  65238. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65239. var rotMat = Bone._tmpMats[1];
  65240. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65241. rotMatInv.multiplyToRef(rotMat, rotMat);
  65242. this._rotateWithMatrix(rotMat, space, mesh);
  65243. };
  65244. /**
  65245. * Set the rotation matrix of the bone in local of world space.
  65246. * @param rotMat The rotation matrix that the bone should be set to.
  65247. * @param space The space that the rotation is in.
  65248. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65249. */
  65250. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65252. var rotMatInv = Bone._tmpMats[0];
  65253. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65254. var rotMat2 = Bone._tmpMats[1];
  65255. rotMat2.copyFrom(rotMat);
  65256. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65257. this._rotateWithMatrix(rotMat2, space, mesh);
  65258. };
  65259. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65261. var lmat = this.getLocalMatrix();
  65262. var lx = lmat.m[12];
  65263. var ly = lmat.m[13];
  65264. var lz = lmat.m[14];
  65265. var parent = this.getParent();
  65266. var parentScale = Bone._tmpMats[3];
  65267. var parentScaleInv = Bone._tmpMats[4];
  65268. if (parent) {
  65269. if (space == BABYLON.Space.WORLD) {
  65270. if (mesh) {
  65271. parentScale.copyFrom(mesh.getWorldMatrix());
  65272. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65273. }
  65274. else {
  65275. parentScale.copyFrom(parent.getAbsoluteTransform());
  65276. }
  65277. }
  65278. else {
  65279. parentScale = parent._scaleMatrix;
  65280. }
  65281. parentScaleInv.copyFrom(parentScale);
  65282. parentScaleInv.invert();
  65283. lmat.multiplyToRef(parentScale, lmat);
  65284. lmat.multiplyToRef(rmat, lmat);
  65285. lmat.multiplyToRef(parentScaleInv, lmat);
  65286. }
  65287. else {
  65288. if (space == BABYLON.Space.WORLD && mesh) {
  65289. parentScale.copyFrom(mesh.getWorldMatrix());
  65290. parentScaleInv.copyFrom(parentScale);
  65291. parentScaleInv.invert();
  65292. lmat.multiplyToRef(parentScale, lmat);
  65293. lmat.multiplyToRef(rmat, lmat);
  65294. lmat.multiplyToRef(parentScaleInv, lmat);
  65295. }
  65296. else {
  65297. lmat.multiplyToRef(rmat, lmat);
  65298. }
  65299. }
  65300. lmat.m[12] = lx;
  65301. lmat.m[13] = ly;
  65302. lmat.m[14] = lz;
  65303. this.computeAbsoluteTransforms();
  65304. this.markAsDirty();
  65305. };
  65306. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65307. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65308. if (space == BABYLON.Space.WORLD) {
  65309. var scaleMatrix = Bone._tmpMats[2];
  65310. scaleMatrix.copyFrom(this._scaleMatrix);
  65311. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65312. if (mesh) {
  65313. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65314. var meshScale = Bone._tmpMats[3];
  65315. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65316. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65317. }
  65318. rotMatInv.invert();
  65319. scaleMatrix.m[0] *= this._scalingDeterminant;
  65320. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65321. }
  65322. else {
  65323. rotMatInv.copyFrom(this.getLocalMatrix());
  65324. rotMatInv.invert();
  65325. var scaleMatrix = Bone._tmpMats[2];
  65326. scaleMatrix.copyFrom(this._scaleMatrix);
  65327. if (this._parent) {
  65328. var pscaleMatrix = Bone._tmpMats[3];
  65329. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65330. pscaleMatrix.invert();
  65331. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65332. }
  65333. else {
  65334. scaleMatrix.m[0] *= this._scalingDeterminant;
  65335. }
  65336. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65337. }
  65338. };
  65339. /**
  65340. * Get the scale of the bone
  65341. * @returns the scale of the bone
  65342. */
  65343. Bone.prototype.getScale = function () {
  65344. return this._scaleVector.clone();
  65345. };
  65346. /**
  65347. * Copy the scale of the bone to a vector3.
  65348. * @param result The vector3 to copy the scale to
  65349. */
  65350. Bone.prototype.getScaleToRef = function (result) {
  65351. result.copyFrom(this._scaleVector);
  65352. };
  65353. /**
  65354. * Get the position of the bone in local or world space.
  65355. * @param space The space that the returned position is in.
  65356. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65357. * @returns The position of the bone
  65358. */
  65359. Bone.prototype.getPosition = function (space, mesh) {
  65360. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65361. if (mesh === void 0) { mesh = null; }
  65362. var pos = BABYLON.Vector3.Zero();
  65363. this.getPositionToRef(space, mesh, pos);
  65364. return pos;
  65365. };
  65366. /**
  65367. * Copy the position of the bone to a vector3 in local or world space.
  65368. * @param space The space that the returned position is in.
  65369. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65370. * @param result The vector3 to copy the position to.
  65371. */
  65372. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65374. if (space == BABYLON.Space.LOCAL) {
  65375. var lm = this.getLocalMatrix();
  65376. result.x = lm.m[12];
  65377. result.y = lm.m[13];
  65378. result.z = lm.m[14];
  65379. }
  65380. else {
  65381. var wm = null;
  65382. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65383. if (mesh) {
  65384. wm = mesh.getWorldMatrix();
  65385. }
  65386. this._skeleton.computeAbsoluteTransforms();
  65387. var tmat = Bone._tmpMats[0];
  65388. if (mesh && wm) {
  65389. tmat.copyFrom(this.getAbsoluteTransform());
  65390. tmat.multiplyToRef(wm, tmat);
  65391. }
  65392. else {
  65393. tmat = this.getAbsoluteTransform();
  65394. }
  65395. result.x = tmat.m[12];
  65396. result.y = tmat.m[13];
  65397. result.z = tmat.m[14];
  65398. }
  65399. };
  65400. /**
  65401. * Get the absolute position of the bone (world space).
  65402. * @param mesh The mesh that this bone is attached to.
  65403. * @returns The absolute position of the bone
  65404. */
  65405. Bone.prototype.getAbsolutePosition = function (mesh) {
  65406. if (mesh === void 0) { mesh = null; }
  65407. var pos = BABYLON.Vector3.Zero();
  65408. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65409. return pos;
  65410. };
  65411. /**
  65412. * Copy the absolute position of the bone (world space) to the result param.
  65413. * @param mesh The mesh that this bone is attached to.
  65414. * @param result The vector3 to copy the absolute position to.
  65415. */
  65416. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65417. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65418. };
  65419. /**
  65420. * Compute the absolute transforms of this bone and its children.
  65421. */
  65422. Bone.prototype.computeAbsoluteTransforms = function () {
  65423. if (this._parent) {
  65424. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65425. }
  65426. else {
  65427. this._absoluteTransform.copyFrom(this._localMatrix);
  65428. var poseMatrix = this._skeleton.getPoseMatrix();
  65429. if (poseMatrix) {
  65430. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65431. }
  65432. }
  65433. var children = this.children;
  65434. var len = children.length;
  65435. for (var i = 0; i < len; i++) {
  65436. children[i].computeAbsoluteTransforms();
  65437. }
  65438. };
  65439. Bone.prototype._syncScaleVector = function () {
  65440. var lm = this.getLocalMatrix();
  65441. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65442. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65443. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65444. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65445. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65446. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65447. this._scaleVector.x = xs * Math.sqrt(xsq);
  65448. this._scaleVector.y = ys * Math.sqrt(ysq);
  65449. this._scaleVector.z = zs * Math.sqrt(zsq);
  65450. if (this._parent) {
  65451. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65452. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65453. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65454. }
  65455. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  65456. };
  65457. /**
  65458. * Get the world direction from an axis that is in the local space of the bone.
  65459. * @param localAxis The local direction that is used to compute the world direction.
  65460. * @param mesh The mesh that this bone is attached to.
  65461. * @returns The world direction
  65462. */
  65463. Bone.prototype.getDirection = function (localAxis, mesh) {
  65464. if (mesh === void 0) { mesh = null; }
  65465. var result = BABYLON.Vector3.Zero();
  65466. this.getDirectionToRef(localAxis, mesh, result);
  65467. return result;
  65468. };
  65469. /**
  65470. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  65471. * @param localAxis The local direction that is used to compute the world direction.
  65472. * @param mesh The mesh that this bone is attached to.
  65473. * @param result The vector3 that the world direction will be copied to.
  65474. */
  65475. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  65476. if (mesh === void 0) { mesh = null; }
  65477. var wm = null;
  65478. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65479. if (mesh) {
  65480. wm = mesh.getWorldMatrix();
  65481. }
  65482. this._skeleton.computeAbsoluteTransforms();
  65483. var mat = Bone._tmpMats[0];
  65484. mat.copyFrom(this.getAbsoluteTransform());
  65485. if (mesh && wm) {
  65486. mat.multiplyToRef(wm, mat);
  65487. }
  65488. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  65489. result.normalize();
  65490. };
  65491. /**
  65492. * Get the euler rotation of the bone in local or world space.
  65493. * @param space The space that the rotation should be in.
  65494. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65495. * @returns The euler rotation
  65496. */
  65497. Bone.prototype.getRotation = function (space, mesh) {
  65498. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65499. if (mesh === void 0) { mesh = null; }
  65500. var result = BABYLON.Vector3.Zero();
  65501. this.getRotationToRef(space, mesh, result);
  65502. return result;
  65503. };
  65504. /**
  65505. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  65506. * @param space The space that the rotation should be in.
  65507. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65508. * @param result The vector3 that the rotation should be copied to.
  65509. */
  65510. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  65511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65512. if (mesh === void 0) { mesh = null; }
  65513. var quat = Bone._tmpQuat;
  65514. this.getRotationQuaternionToRef(space, mesh, quat);
  65515. quat.toEulerAnglesToRef(result);
  65516. };
  65517. /**
  65518. * Get the quaternion rotation of the bone in either local or world space.
  65519. * @param space The space that the rotation should be in.
  65520. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65521. * @returns The quaternion rotation
  65522. */
  65523. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  65524. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65525. if (mesh === void 0) { mesh = null; }
  65526. var result = BABYLON.Quaternion.Identity();
  65527. this.getRotationQuaternionToRef(space, mesh, result);
  65528. return result;
  65529. };
  65530. /**
  65531. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  65532. * @param space The space that the rotation should be in.
  65533. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65534. * @param result The quaternion that the rotation should be copied to.
  65535. */
  65536. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  65537. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65538. if (mesh === void 0) { mesh = null; }
  65539. if (space == BABYLON.Space.LOCAL) {
  65540. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65541. }
  65542. else {
  65543. var mat = Bone._tmpMats[0];
  65544. var amat = this.getAbsoluteTransform();
  65545. if (mesh) {
  65546. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65547. }
  65548. else {
  65549. mat.copyFrom(amat);
  65550. }
  65551. mat.m[0] *= this._scalingDeterminant;
  65552. mat.m[1] *= this._scalingDeterminant;
  65553. mat.m[2] *= this._scalingDeterminant;
  65554. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65555. }
  65556. };
  65557. /**
  65558. * Get the rotation matrix of the bone in local or world space.
  65559. * @param space The space that the rotation should be in.
  65560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65561. * @returns The rotation matrix
  65562. */
  65563. Bone.prototype.getRotationMatrix = function (space, mesh) {
  65564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65565. var result = BABYLON.Matrix.Identity();
  65566. this.getRotationMatrixToRef(space, mesh, result);
  65567. return result;
  65568. };
  65569. /**
  65570. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  65571. * @param space The space that the rotation should be in.
  65572. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65573. * @param result The quaternion that the rotation should be copied to.
  65574. */
  65575. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  65576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65577. if (space == BABYLON.Space.LOCAL) {
  65578. this.getLocalMatrix().getRotationMatrixToRef(result);
  65579. }
  65580. else {
  65581. var mat = Bone._tmpMats[0];
  65582. var amat = this.getAbsoluteTransform();
  65583. if (mesh) {
  65584. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65585. }
  65586. else {
  65587. mat.copyFrom(amat);
  65588. }
  65589. mat.m[0] *= this._scalingDeterminant;
  65590. mat.m[1] *= this._scalingDeterminant;
  65591. mat.m[2] *= this._scalingDeterminant;
  65592. mat.getRotationMatrixToRef(result);
  65593. }
  65594. };
  65595. /**
  65596. * Get the world position of a point that is in the local space of the bone.
  65597. * @param position The local position
  65598. * @param mesh The mesh that this bone is attached to.
  65599. * @returns The world position
  65600. */
  65601. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  65602. if (mesh === void 0) { mesh = null; }
  65603. var result = BABYLON.Vector3.Zero();
  65604. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  65605. return result;
  65606. };
  65607. /**
  65608. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  65609. * @param position The local position
  65610. * @param mesh The mesh that this bone is attached to.
  65611. * @param result The vector3 that the world position should be copied to.
  65612. */
  65613. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  65614. if (mesh === void 0) { mesh = null; }
  65615. var wm = null;
  65616. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65617. if (mesh) {
  65618. wm = mesh.getWorldMatrix();
  65619. }
  65620. this._skeleton.computeAbsoluteTransforms();
  65621. var tmat = Bone._tmpMats[0];
  65622. if (mesh && wm) {
  65623. tmat.copyFrom(this.getAbsoluteTransform());
  65624. tmat.multiplyToRef(wm, tmat);
  65625. }
  65626. else {
  65627. tmat = this.getAbsoluteTransform();
  65628. }
  65629. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65630. };
  65631. /**
  65632. * Get the local position of a point that is in world space.
  65633. * @param position The world position
  65634. * @param mesh The mesh that this bone is attached to.
  65635. * @returns The local position
  65636. */
  65637. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  65638. if (mesh === void 0) { mesh = null; }
  65639. var result = BABYLON.Vector3.Zero();
  65640. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  65641. return result;
  65642. };
  65643. /**
  65644. * Get the local position of a point that is in world space and copy it to the result param.
  65645. * @param position The world position
  65646. * @param mesh The mesh that this bone is attached to.
  65647. * @param result The vector3 that the local position should be copied to.
  65648. */
  65649. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  65650. if (mesh === void 0) { mesh = null; }
  65651. var wm = null;
  65652. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65653. if (mesh) {
  65654. wm = mesh.getWorldMatrix();
  65655. }
  65656. this._skeleton.computeAbsoluteTransforms();
  65657. var tmat = Bone._tmpMats[0];
  65658. tmat.copyFrom(this.getAbsoluteTransform());
  65659. if (mesh && wm) {
  65660. tmat.multiplyToRef(wm, tmat);
  65661. }
  65662. tmat.invert();
  65663. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65664. };
  65665. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65666. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  65667. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65668. return Bone;
  65669. }(BABYLON.Node));
  65670. BABYLON.Bone = Bone;
  65671. })(BABYLON || (BABYLON = {}));
  65672. //# sourceMappingURL=babylon.bone.js.map
  65673. var BABYLON;
  65674. (function (BABYLON) {
  65675. var BoneIKController = /** @class */ (function () {
  65676. function BoneIKController(mesh, bone, options) {
  65677. this.targetPosition = BABYLON.Vector3.Zero();
  65678. this.poleTargetPosition = BABYLON.Vector3.Zero();
  65679. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  65680. this.poleAngle = 0;
  65681. this.slerpAmount = 1;
  65682. this._bone1Quat = BABYLON.Quaternion.Identity();
  65683. this._bone1Mat = BABYLON.Matrix.Identity();
  65684. this._bone2Ang = Math.PI;
  65685. this._maxAngle = Math.PI;
  65686. this._rightHandedSystem = false;
  65687. this._bendAxis = BABYLON.Vector3.Right();
  65688. this._slerping = false;
  65689. this._adjustRoll = 0;
  65690. this._bone2 = bone;
  65691. this._bone1 = bone.getParent();
  65692. if (!this._bone1) {
  65693. return;
  65694. }
  65695. this.mesh = mesh;
  65696. var bonePos = bone.getPosition();
  65697. if (bone.getAbsoluteTransform().determinant() > 0) {
  65698. this._rightHandedSystem = true;
  65699. this._bendAxis.x = 0;
  65700. this._bendAxis.y = 0;
  65701. this._bendAxis.z = -1;
  65702. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  65703. this._adjustRoll = Math.PI * .5;
  65704. this._bendAxis.z = 1;
  65705. }
  65706. }
  65707. if (this._bone1.length) {
  65708. var boneScale1 = this._bone1.getScale();
  65709. var boneScale2 = this._bone2.getScale();
  65710. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  65711. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  65712. }
  65713. else if (this._bone1.children[0]) {
  65714. mesh.computeWorldMatrix(true);
  65715. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  65716. var pos2 = this._bone2.getAbsolutePosition(mesh);
  65717. var pos3 = this._bone1.getAbsolutePosition(mesh);
  65718. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  65719. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  65720. }
  65721. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  65722. this.maxAngle = Math.PI;
  65723. if (options) {
  65724. if (options.targetMesh) {
  65725. this.targetMesh = options.targetMesh;
  65726. this.targetMesh.computeWorldMatrix(true);
  65727. }
  65728. if (options.poleTargetMesh) {
  65729. this.poleTargetMesh = options.poleTargetMesh;
  65730. this.poleTargetMesh.computeWorldMatrix(true);
  65731. }
  65732. else if (options.poleTargetBone) {
  65733. this.poleTargetBone = options.poleTargetBone;
  65734. }
  65735. else if (this._bone1.getParent()) {
  65736. this.poleTargetBone = this._bone1.getParent();
  65737. }
  65738. if (options.poleTargetLocalOffset) {
  65739. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  65740. }
  65741. if (options.poleAngle) {
  65742. this.poleAngle = options.poleAngle;
  65743. }
  65744. if (options.bendAxis) {
  65745. this._bendAxis.copyFrom(options.bendAxis);
  65746. }
  65747. if (options.maxAngle) {
  65748. this.maxAngle = options.maxAngle;
  65749. }
  65750. if (options.slerpAmount) {
  65751. this.slerpAmount = options.slerpAmount;
  65752. }
  65753. }
  65754. }
  65755. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  65756. get: function () {
  65757. return this._maxAngle;
  65758. },
  65759. set: function (value) {
  65760. this._setMaxAngle(value);
  65761. },
  65762. enumerable: true,
  65763. configurable: true
  65764. });
  65765. BoneIKController.prototype._setMaxAngle = function (ang) {
  65766. if (ang < 0) {
  65767. ang = 0;
  65768. }
  65769. if (ang > Math.PI || ang == undefined) {
  65770. ang = Math.PI;
  65771. }
  65772. this._maxAngle = ang;
  65773. var a = this._bone1Length;
  65774. var b = this._bone2Length;
  65775. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  65776. };
  65777. BoneIKController.prototype.update = function () {
  65778. var bone1 = this._bone1;
  65779. if (!bone1) {
  65780. return;
  65781. }
  65782. var target = this.targetPosition;
  65783. var poleTarget = this.poleTargetPosition;
  65784. var mat1 = BoneIKController._tmpMats[0];
  65785. var mat2 = BoneIKController._tmpMats[1];
  65786. if (this.targetMesh) {
  65787. target.copyFrom(this.targetMesh.getAbsolutePosition());
  65788. }
  65789. if (this.poleTargetBone) {
  65790. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  65791. }
  65792. else if (this.poleTargetMesh) {
  65793. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  65794. }
  65795. var bonePos = BoneIKController._tmpVecs[0];
  65796. var zaxis = BoneIKController._tmpVecs[1];
  65797. var xaxis = BoneIKController._tmpVecs[2];
  65798. var yaxis = BoneIKController._tmpVecs[3];
  65799. var upAxis = BoneIKController._tmpVecs[4];
  65800. var _tmpQuat = BoneIKController._tmpQuat;
  65801. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  65802. poleTarget.subtractToRef(bonePos, upAxis);
  65803. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  65804. upAxis.y = 1;
  65805. }
  65806. else {
  65807. upAxis.normalize();
  65808. }
  65809. target.subtractToRef(bonePos, yaxis);
  65810. yaxis.normalize();
  65811. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  65812. zaxis.normalize();
  65813. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  65814. xaxis.normalize();
  65815. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  65816. var a = this._bone1Length;
  65817. var b = this._bone2Length;
  65818. var c = BABYLON.Vector3.Distance(bonePos, target);
  65819. if (this._maxReach > 0) {
  65820. c = Math.min(this._maxReach, c);
  65821. }
  65822. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  65823. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  65824. if (acosa > 1) {
  65825. acosa = 1;
  65826. }
  65827. if (acosb > 1) {
  65828. acosb = 1;
  65829. }
  65830. if (acosa < -1) {
  65831. acosa = -1;
  65832. }
  65833. if (acosb < -1) {
  65834. acosb = -1;
  65835. }
  65836. var angA = Math.acos(acosa);
  65837. var angB = Math.acos(acosb);
  65838. var angC = -angA - angB;
  65839. if (this._rightHandedSystem) {
  65840. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  65841. mat2.multiplyToRef(mat1, mat1);
  65842. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  65843. mat2.multiplyToRef(mat1, mat1);
  65844. }
  65845. else {
  65846. var _tmpVec = BoneIKController._tmpVecs[5];
  65847. _tmpVec.copyFrom(this._bendAxis);
  65848. _tmpVec.x *= -1;
  65849. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  65850. mat2.multiplyToRef(mat1, mat1);
  65851. }
  65852. if (this.poleAngle) {
  65853. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  65854. mat1.multiplyToRef(mat2, mat1);
  65855. }
  65856. if (this._bone1) {
  65857. if (this.slerpAmount < 1) {
  65858. if (!this._slerping) {
  65859. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  65860. }
  65861. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  65862. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  65863. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  65864. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  65865. this._slerping = true;
  65866. }
  65867. else {
  65868. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  65869. this._bone1Mat.copyFrom(mat1);
  65870. this._slerping = false;
  65871. }
  65872. }
  65873. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  65874. this._bone2Ang = angC;
  65875. };
  65876. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65877. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  65878. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65879. return BoneIKController;
  65880. }());
  65881. BABYLON.BoneIKController = BoneIKController;
  65882. })(BABYLON || (BABYLON = {}));
  65883. //# sourceMappingURL=babylon.boneIKController.js.map
  65884. var BABYLON;
  65885. (function (BABYLON) {
  65886. var BoneLookController = /** @class */ (function () {
  65887. /**
  65888. * Create a BoneLookController
  65889. * @param mesh the mesh that the bone belongs to
  65890. * @param bone the bone that will be looking to the target
  65891. * @param target the target Vector3 to look at
  65892. * @param settings optional settings:
  65893. * - maxYaw: the maximum angle the bone will yaw to
  65894. * - minYaw: the minimum angle the bone will yaw to
  65895. * - maxPitch: the maximum angle the bone will pitch to
  65896. * - minPitch: the minimum angle the bone will yaw to
  65897. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  65898. * - upAxis: the up axis of the coordinate system
  65899. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  65900. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  65901. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  65902. * - adjustYaw: used to make an adjustment to the yaw of the bone
  65903. * - adjustPitch: used to make an adjustment to the pitch of the bone
  65904. * - adjustRoll: used to make an adjustment to the roll of the bone
  65905. **/
  65906. function BoneLookController(mesh, bone, target, options) {
  65907. /**
  65908. * The up axis of the coordinate system that is used when the bone is rotated.
  65909. */
  65910. this.upAxis = BABYLON.Vector3.Up();
  65911. /**
  65912. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  65913. */
  65914. this.upAxisSpace = BABYLON.Space.LOCAL;
  65915. /**
  65916. * Used to make an adjustment to the yaw of the bone.
  65917. */
  65918. this.adjustYaw = 0;
  65919. /**
  65920. * Used to make an adjustment to the pitch of the bone.
  65921. */
  65922. this.adjustPitch = 0;
  65923. /**
  65924. * Used to make an adjustment to the roll of the bone.
  65925. */
  65926. this.adjustRoll = 0;
  65927. /**
  65928. * 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).
  65929. */
  65930. this.slerpAmount = 1;
  65931. this._boneQuat = BABYLON.Quaternion.Identity();
  65932. this._slerping = false;
  65933. this._firstFrameSkipped = false;
  65934. this._fowardAxis = BABYLON.Vector3.Forward();
  65935. this.mesh = mesh;
  65936. this.bone = bone;
  65937. this.target = target;
  65938. if (options) {
  65939. if (options.adjustYaw) {
  65940. this.adjustYaw = options.adjustYaw;
  65941. }
  65942. if (options.adjustPitch) {
  65943. this.adjustPitch = options.adjustPitch;
  65944. }
  65945. if (options.adjustRoll) {
  65946. this.adjustRoll = options.adjustRoll;
  65947. }
  65948. if (options.maxYaw != null) {
  65949. this.maxYaw = options.maxYaw;
  65950. }
  65951. else {
  65952. this.maxYaw = Math.PI;
  65953. }
  65954. if (options.minYaw != null) {
  65955. this.minYaw = options.minYaw;
  65956. }
  65957. else {
  65958. this.minYaw = -Math.PI;
  65959. }
  65960. if (options.maxPitch != null) {
  65961. this.maxPitch = options.maxPitch;
  65962. }
  65963. else {
  65964. this.maxPitch = Math.PI;
  65965. }
  65966. if (options.minPitch != null) {
  65967. this.minPitch = options.minPitch;
  65968. }
  65969. else {
  65970. this.minPitch = -Math.PI;
  65971. }
  65972. if (options.slerpAmount != null) {
  65973. this.slerpAmount = options.slerpAmount;
  65974. }
  65975. if (options.upAxis != null) {
  65976. this.upAxis = options.upAxis;
  65977. }
  65978. if (options.upAxisSpace != null) {
  65979. this.upAxisSpace = options.upAxisSpace;
  65980. }
  65981. if (options.yawAxis != null || options.pitchAxis != null) {
  65982. var newYawAxis = BABYLON.Axis.Y;
  65983. var newPitchAxis = BABYLON.Axis.X;
  65984. if (options.yawAxis != null) {
  65985. newYawAxis = options.yawAxis.clone();
  65986. newYawAxis.normalize();
  65987. }
  65988. if (options.pitchAxis != null) {
  65989. newPitchAxis = options.pitchAxis.clone();
  65990. newPitchAxis.normalize();
  65991. }
  65992. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  65993. this._transformYawPitch = BABYLON.Matrix.Identity();
  65994. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  65995. this._transformYawPitchInv = this._transformYawPitch.clone();
  65996. this._transformYawPitch.invert();
  65997. }
  65998. }
  65999. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66000. this.upAxisSpace = BABYLON.Space.LOCAL;
  66001. }
  66002. }
  66003. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66004. /**
  66005. * Get/set the minimum yaw angle that the bone can look to.
  66006. */
  66007. get: function () {
  66008. return this._minYaw;
  66009. },
  66010. set: function (value) {
  66011. this._minYaw = value;
  66012. this._minYawSin = Math.sin(value);
  66013. this._minYawCos = Math.cos(value);
  66014. if (this._maxYaw != null) {
  66015. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66016. this._yawRange = this._maxYaw - this._minYaw;
  66017. }
  66018. },
  66019. enumerable: true,
  66020. configurable: true
  66021. });
  66022. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66023. /**
  66024. * Get/set the maximum yaw angle that the bone can look to.
  66025. */
  66026. get: function () {
  66027. return this._maxYaw;
  66028. },
  66029. set: function (value) {
  66030. this._maxYaw = value;
  66031. this._maxYawSin = Math.sin(value);
  66032. this._maxYawCos = Math.cos(value);
  66033. if (this._minYaw != null) {
  66034. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66035. this._yawRange = this._maxYaw - this._minYaw;
  66036. }
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66042. /**
  66043. * Get/set the minimum pitch angle that the bone can look to.
  66044. */
  66045. get: function () {
  66046. return this._minPitch;
  66047. },
  66048. set: function (value) {
  66049. this._minPitch = value;
  66050. this._minPitchTan = Math.tan(value);
  66051. },
  66052. enumerable: true,
  66053. configurable: true
  66054. });
  66055. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66056. /**
  66057. * Get/set the maximum pitch angle that the bone can look to.
  66058. */
  66059. get: function () {
  66060. return this._maxPitch;
  66061. },
  66062. set: function (value) {
  66063. this._maxPitch = value;
  66064. this._maxPitchTan = Math.tan(value);
  66065. },
  66066. enumerable: true,
  66067. configurable: true
  66068. });
  66069. /**
  66070. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66071. */
  66072. BoneLookController.prototype.update = function () {
  66073. //skip the first frame when slerping so that the mesh rotation is correct
  66074. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66075. this._firstFrameSkipped = true;
  66076. return;
  66077. }
  66078. var bone = this.bone;
  66079. var bonePos = BoneLookController._tmpVecs[0];
  66080. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66081. var target = this.target;
  66082. var _tmpMat1 = BoneLookController._tmpMats[0];
  66083. var _tmpMat2 = BoneLookController._tmpMats[1];
  66084. var mesh = this.mesh;
  66085. var parentBone = bone.getParent();
  66086. var upAxis = BoneLookController._tmpVecs[1];
  66087. upAxis.copyFrom(this.upAxis);
  66088. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66089. if (this._transformYawPitch) {
  66090. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66091. }
  66092. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66093. }
  66094. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66095. mesh.getDirectionToRef(upAxis, upAxis);
  66096. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66097. upAxis.normalize();
  66098. }
  66099. }
  66100. var checkYaw = false;
  66101. var checkPitch = false;
  66102. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66103. checkYaw = true;
  66104. }
  66105. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66106. checkPitch = true;
  66107. }
  66108. if (checkYaw || checkPitch) {
  66109. var spaceMat = BoneLookController._tmpMats[2];
  66110. var spaceMatInv = BoneLookController._tmpMats[3];
  66111. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66112. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66113. }
  66114. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66115. spaceMat.copyFrom(mesh.getWorldMatrix());
  66116. }
  66117. else {
  66118. var forwardAxis = BoneLookController._tmpVecs[2];
  66119. forwardAxis.copyFrom(this._fowardAxis);
  66120. if (this._transformYawPitch) {
  66121. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66122. }
  66123. if (parentBone) {
  66124. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66125. }
  66126. else {
  66127. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66128. }
  66129. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66130. rightAxis.normalize();
  66131. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66132. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66133. }
  66134. spaceMat.invertToRef(spaceMatInv);
  66135. var xzlen = null;
  66136. if (checkPitch) {
  66137. var localTarget = BoneLookController._tmpVecs[3];
  66138. target.subtractToRef(bonePos, localTarget);
  66139. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66140. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66141. var pitch = Math.atan2(localTarget.y, xzlen);
  66142. var newPitch = pitch;
  66143. if (pitch > this._maxPitch) {
  66144. localTarget.y = this._maxPitchTan * xzlen;
  66145. newPitch = this._maxPitch;
  66146. }
  66147. else if (pitch < this._minPitch) {
  66148. localTarget.y = this._minPitchTan * xzlen;
  66149. newPitch = this._minPitch;
  66150. }
  66151. if (pitch != newPitch) {
  66152. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66153. localTarget.addInPlace(bonePos);
  66154. target = localTarget;
  66155. }
  66156. }
  66157. if (checkYaw) {
  66158. var localTarget = BoneLookController._tmpVecs[4];
  66159. target.subtractToRef(bonePos, localTarget);
  66160. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66161. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66162. var newYaw = yaw;
  66163. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66164. if (xzlen == null) {
  66165. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66166. }
  66167. if (this._yawRange > Math.PI) {
  66168. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66169. localTarget.z = this._maxYawCos * xzlen;
  66170. localTarget.x = this._maxYawSin * xzlen;
  66171. newYaw = this._maxYaw;
  66172. }
  66173. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66174. localTarget.z = this._minYawCos * xzlen;
  66175. localTarget.x = this._minYawSin * xzlen;
  66176. newYaw = this._minYaw;
  66177. }
  66178. }
  66179. else {
  66180. if (yaw > this._maxYaw) {
  66181. localTarget.z = this._maxYawCos * xzlen;
  66182. localTarget.x = this._maxYawSin * xzlen;
  66183. newYaw = this._maxYaw;
  66184. }
  66185. else if (yaw < this._minYaw) {
  66186. localTarget.z = this._minYawCos * xzlen;
  66187. localTarget.x = this._minYawSin * xzlen;
  66188. newYaw = this._minYaw;
  66189. }
  66190. }
  66191. }
  66192. if (this._slerping && this._yawRange > Math.PI) {
  66193. //are we going to be crossing into the min/max region?
  66194. var boneFwd = BoneLookController._tmpVecs[8];
  66195. boneFwd.copyFrom(BABYLON.Axis.Z);
  66196. if (this._transformYawPitch) {
  66197. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66198. }
  66199. var boneRotMat = BoneLookController._tmpMats[4];
  66200. this._boneQuat.toRotationMatrix(boneRotMat);
  66201. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66202. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66203. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66204. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66205. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66206. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66207. if (angBtwTar > angBtwMidYaw) {
  66208. if (xzlen == null) {
  66209. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66210. }
  66211. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66212. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66213. if (angBtwMin < angBtwMax) {
  66214. newYaw = boneYaw + Math.PI * .75;
  66215. localTarget.z = Math.cos(newYaw) * xzlen;
  66216. localTarget.x = Math.sin(newYaw) * xzlen;
  66217. }
  66218. else {
  66219. newYaw = boneYaw - Math.PI * .75;
  66220. localTarget.z = Math.cos(newYaw) * xzlen;
  66221. localTarget.x = Math.sin(newYaw) * xzlen;
  66222. }
  66223. }
  66224. }
  66225. if (yaw != newYaw) {
  66226. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66227. localTarget.addInPlace(bonePos);
  66228. target = localTarget;
  66229. }
  66230. }
  66231. }
  66232. var zaxis = BoneLookController._tmpVecs[5];
  66233. var xaxis = BoneLookController._tmpVecs[6];
  66234. var yaxis = BoneLookController._tmpVecs[7];
  66235. var _tmpQuat = BoneLookController._tmpQuat;
  66236. target.subtractToRef(bonePos, zaxis);
  66237. zaxis.normalize();
  66238. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66239. xaxis.normalize();
  66240. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66241. yaxis.normalize();
  66242. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66243. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66244. return;
  66245. }
  66246. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66247. return;
  66248. }
  66249. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66250. return;
  66251. }
  66252. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66253. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66254. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66255. }
  66256. if (this.slerpAmount < 1) {
  66257. if (!this._slerping) {
  66258. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66259. }
  66260. if (this._transformYawPitch) {
  66261. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66262. }
  66263. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66264. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66265. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66266. this._slerping = true;
  66267. }
  66268. else {
  66269. if (this._transformYawPitch) {
  66270. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66271. }
  66272. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66273. this._slerping = false;
  66274. }
  66275. };
  66276. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66277. var angDiff = ang2 - ang1;
  66278. angDiff %= Math.PI * 2;
  66279. if (angDiff > Math.PI) {
  66280. angDiff -= Math.PI * 2;
  66281. }
  66282. else if (angDiff < -Math.PI) {
  66283. angDiff += Math.PI * 2;
  66284. }
  66285. return angDiff;
  66286. };
  66287. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66288. ang1 %= (2 * Math.PI);
  66289. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66290. ang2 %= (2 * Math.PI);
  66291. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66292. var ab = 0;
  66293. if (ang1 < ang2) {
  66294. ab = ang2 - ang1;
  66295. }
  66296. else {
  66297. ab = ang1 - ang2;
  66298. }
  66299. if (ab > Math.PI) {
  66300. ab = Math.PI * 2 - ab;
  66301. }
  66302. return ab;
  66303. };
  66304. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66305. ang %= (2 * Math.PI);
  66306. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66307. ang1 %= (2 * Math.PI);
  66308. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66309. ang2 %= (2 * Math.PI);
  66310. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66311. if (ang1 < ang2) {
  66312. if (ang > ang1 && ang < ang2) {
  66313. return true;
  66314. }
  66315. }
  66316. else {
  66317. if (ang > ang2 && ang < ang1) {
  66318. return true;
  66319. }
  66320. }
  66321. return false;
  66322. };
  66323. 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()];
  66324. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66325. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66326. return BoneLookController;
  66327. }());
  66328. BABYLON.BoneLookController = BoneLookController;
  66329. })(BABYLON || (BABYLON = {}));
  66330. //# sourceMappingURL=babylon.boneLookController.js.map
  66331. var BABYLON;
  66332. (function (BABYLON) {
  66333. var Skeleton = /** @class */ (function () {
  66334. function Skeleton(name, id, scene) {
  66335. this.name = name;
  66336. this.id = id;
  66337. this.bones = new Array();
  66338. this.needInitialSkinMatrix = false;
  66339. this._isDirty = true;
  66340. this._meshesWithPoseMatrix = new Array();
  66341. this._identity = BABYLON.Matrix.Identity();
  66342. this._ranges = {};
  66343. this._lastAbsoluteTransformsUpdateId = -1;
  66344. // Events
  66345. /**
  66346. * An event triggered before computing the skeleton's matrices
  66347. * @type {BABYLON.Observable}
  66348. */
  66349. this.onBeforeComputeObservable = new BABYLON.Observable();
  66350. this.bones = [];
  66351. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66352. scene.skeletons.push(this);
  66353. //make sure it will recalculate the matrix next time prepare is called.
  66354. this._isDirty = true;
  66355. }
  66356. // Members
  66357. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66358. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66359. return mesh._bonesTransformMatrices;
  66360. }
  66361. if (!this._transformMatrices) {
  66362. this.prepare();
  66363. }
  66364. return this._transformMatrices;
  66365. };
  66366. Skeleton.prototype.getScene = function () {
  66367. return this._scene;
  66368. };
  66369. // Methods
  66370. /**
  66371. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66372. */
  66373. Skeleton.prototype.toString = function (fullDetails) {
  66374. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66375. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66376. if (fullDetails) {
  66377. ret += ", Ranges: {";
  66378. var first = true;
  66379. for (var name_1 in this._ranges) {
  66380. if (first) {
  66381. ret += ", ";
  66382. first = false;
  66383. }
  66384. ret += name_1;
  66385. }
  66386. ret += "}";
  66387. }
  66388. return ret;
  66389. };
  66390. /**
  66391. * Get bone's index searching by name
  66392. * @param {string} name is bone's name to search for
  66393. * @return {number} Indice of the bone. Returns -1 if not found
  66394. */
  66395. Skeleton.prototype.getBoneIndexByName = function (name) {
  66396. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66397. if (this.bones[boneIndex].name === name) {
  66398. return boneIndex;
  66399. }
  66400. }
  66401. return -1;
  66402. };
  66403. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66404. // check name not already in use
  66405. if (!this._ranges[name]) {
  66406. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66407. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66408. if (this.bones[i].animations[0]) {
  66409. this.bones[i].animations[0].createRange(name, from, to);
  66410. }
  66411. }
  66412. }
  66413. };
  66414. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66415. if (deleteFrames === void 0) { deleteFrames = true; }
  66416. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66417. if (this.bones[i].animations[0]) {
  66418. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66419. }
  66420. }
  66421. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66422. };
  66423. Skeleton.prototype.getAnimationRange = function (name) {
  66424. return this._ranges[name];
  66425. };
  66426. /**
  66427. * Returns as an Array, all AnimationRanges defined on this skeleton
  66428. */
  66429. Skeleton.prototype.getAnimationRanges = function () {
  66430. var animationRanges = [];
  66431. var name;
  66432. var i = 0;
  66433. for (name in this._ranges) {
  66434. animationRanges[i] = this._ranges[name];
  66435. i++;
  66436. }
  66437. return animationRanges;
  66438. };
  66439. /**
  66440. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66441. */
  66442. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66443. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66444. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66445. return false;
  66446. }
  66447. var ret = true;
  66448. var frameOffset = this._getHighestAnimationFrame() + 1;
  66449. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66450. var boneDict = {};
  66451. var sourceBones = source.bones;
  66452. var nBones;
  66453. var i;
  66454. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66455. boneDict[sourceBones[i].name] = sourceBones[i];
  66456. }
  66457. if (this.bones.length !== sourceBones.length) {
  66458. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66459. ret = false;
  66460. }
  66461. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66462. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66463. var boneName = this.bones[i].name;
  66464. var sourceBone = boneDict[boneName];
  66465. if (sourceBone) {
  66466. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66467. }
  66468. else {
  66469. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  66470. ret = false;
  66471. }
  66472. }
  66473. // do not call createAnimationRange(), since it also is done to bones, which was already done
  66474. var range = source.getAnimationRange(name);
  66475. if (range) {
  66476. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  66477. }
  66478. return ret;
  66479. };
  66480. Skeleton.prototype.returnToRest = function () {
  66481. for (var index = 0; index < this.bones.length; index++) {
  66482. this.bones[index].returnToRest();
  66483. }
  66484. };
  66485. Skeleton.prototype._getHighestAnimationFrame = function () {
  66486. var ret = 0;
  66487. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66488. if (this.bones[i].animations[0]) {
  66489. var highest = this.bones[i].animations[0].getHighestFrame();
  66490. if (ret < highest) {
  66491. ret = highest;
  66492. }
  66493. }
  66494. }
  66495. return ret;
  66496. };
  66497. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  66498. var range = this.getAnimationRange(name);
  66499. if (!range) {
  66500. return null;
  66501. }
  66502. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  66503. };
  66504. Skeleton.prototype._markAsDirty = function () {
  66505. this._isDirty = true;
  66506. };
  66507. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  66508. this._meshesWithPoseMatrix.push(mesh);
  66509. };
  66510. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  66511. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  66512. if (index > -1) {
  66513. this._meshesWithPoseMatrix.splice(index, 1);
  66514. }
  66515. };
  66516. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  66517. this.onBeforeComputeObservable.notifyObservers(this);
  66518. for (var index = 0; index < this.bones.length; index++) {
  66519. var bone = this.bones[index];
  66520. var parentBone = bone.getParent();
  66521. if (parentBone) {
  66522. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  66523. }
  66524. else {
  66525. if (initialSkinMatrix) {
  66526. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  66527. }
  66528. else {
  66529. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  66530. }
  66531. }
  66532. if (bone._index !== -1) {
  66533. var mappedIndex = bone._index === null ? index : bone._index;
  66534. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  66535. }
  66536. }
  66537. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  66538. };
  66539. Skeleton.prototype.prepare = function () {
  66540. if (!this._isDirty) {
  66541. return;
  66542. }
  66543. if (this.needInitialSkinMatrix) {
  66544. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  66545. var mesh = this._meshesWithPoseMatrix[index];
  66546. var poseMatrix = mesh.getPoseMatrix();
  66547. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  66548. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66549. }
  66550. if (this._synchronizedWithMesh !== mesh) {
  66551. this._synchronizedWithMesh = mesh;
  66552. // Prepare bones
  66553. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  66554. var bone = this.bones[boneIndex];
  66555. if (!bone.getParent()) {
  66556. var matrix = bone.getBaseMatrix();
  66557. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  66558. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  66559. }
  66560. }
  66561. }
  66562. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  66563. }
  66564. }
  66565. else {
  66566. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  66567. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66568. }
  66569. this._computeTransformMatrices(this._transformMatrices, null);
  66570. }
  66571. this._isDirty = false;
  66572. this._scene._activeBones.addCount(this.bones.length, false);
  66573. };
  66574. Skeleton.prototype.getAnimatables = function () {
  66575. if (!this._animatables || this._animatables.length !== this.bones.length) {
  66576. this._animatables = [];
  66577. for (var index = 0; index < this.bones.length; index++) {
  66578. this._animatables.push(this.bones[index]);
  66579. }
  66580. }
  66581. return this._animatables;
  66582. };
  66583. Skeleton.prototype.clone = function (name, id) {
  66584. var result = new Skeleton(name, id || name, this._scene);
  66585. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66586. for (var index = 0; index < this.bones.length; index++) {
  66587. var source = this.bones[index];
  66588. var parentBone = null;
  66589. var parent_1 = source.getParent();
  66590. if (parent_1) {
  66591. var parentIndex = this.bones.indexOf(parent_1);
  66592. parentBone = result.bones[parentIndex];
  66593. }
  66594. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  66595. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  66596. }
  66597. if (this._ranges) {
  66598. result._ranges = {};
  66599. for (var rangeName in this._ranges) {
  66600. var range = this._ranges[rangeName];
  66601. if (range) {
  66602. result._ranges[rangeName] = range.clone();
  66603. }
  66604. }
  66605. }
  66606. this._isDirty = true;
  66607. return result;
  66608. };
  66609. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  66610. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  66611. this.bones.forEach(function (bone) {
  66612. bone.animations.forEach(function (animation) {
  66613. animation.enableBlending = true;
  66614. animation.blendingSpeed = blendingSpeed;
  66615. });
  66616. });
  66617. };
  66618. Skeleton.prototype.dispose = function () {
  66619. this._meshesWithPoseMatrix = [];
  66620. // Animations
  66621. this.getScene().stopAnimation(this);
  66622. // Remove from scene
  66623. this.getScene().removeSkeleton(this);
  66624. };
  66625. Skeleton.prototype.serialize = function () {
  66626. var serializationObject = {};
  66627. serializationObject.name = this.name;
  66628. serializationObject.id = this.id;
  66629. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  66630. serializationObject.bones = [];
  66631. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66632. for (var index = 0; index < this.bones.length; index++) {
  66633. var bone = this.bones[index];
  66634. var parent_2 = bone.getParent();
  66635. var serializedBone = {
  66636. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  66637. name: bone.name,
  66638. matrix: bone.getBaseMatrix().toArray(),
  66639. rest: bone.getRestPose().toArray()
  66640. };
  66641. serializationObject.bones.push(serializedBone);
  66642. if (bone.length) {
  66643. serializedBone.length = bone.length;
  66644. }
  66645. if (bone.animations && bone.animations.length > 0) {
  66646. serializedBone.animation = bone.animations[0].serialize();
  66647. }
  66648. serializationObject.ranges = [];
  66649. for (var name in this._ranges) {
  66650. var source = this._ranges[name];
  66651. if (!source) {
  66652. continue;
  66653. }
  66654. var range = {};
  66655. range.name = name;
  66656. range.from = source.from;
  66657. range.to = source.to;
  66658. serializationObject.ranges.push(range);
  66659. }
  66660. }
  66661. return serializationObject;
  66662. };
  66663. Skeleton.Parse = function (parsedSkeleton, scene) {
  66664. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  66665. if (parsedSkeleton.dimensionsAtRest) {
  66666. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  66667. }
  66668. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  66669. var index;
  66670. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  66671. var parsedBone = parsedSkeleton.bones[index];
  66672. var parentBone = null;
  66673. if (parsedBone.parentBoneIndex > -1) {
  66674. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  66675. }
  66676. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  66677. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  66678. if (parsedBone.length) {
  66679. bone.length = parsedBone.length;
  66680. }
  66681. if (parsedBone.animation) {
  66682. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  66683. }
  66684. }
  66685. // placed after bones, so createAnimationRange can cascade down
  66686. if (parsedSkeleton.ranges) {
  66687. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  66688. var data = parsedSkeleton.ranges[index];
  66689. skeleton.createAnimationRange(data.name, data.from, data.to);
  66690. }
  66691. }
  66692. return skeleton;
  66693. };
  66694. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  66695. if (forceUpdate === void 0) { forceUpdate = false; }
  66696. var renderId = this._scene.getRenderId();
  66697. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  66698. this.bones[0].computeAbsoluteTransforms();
  66699. this._lastAbsoluteTransformsUpdateId = renderId;
  66700. }
  66701. };
  66702. Skeleton.prototype.getPoseMatrix = function () {
  66703. var poseMatrix = null;
  66704. if (this._meshesWithPoseMatrix.length > 0) {
  66705. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  66706. }
  66707. return poseMatrix;
  66708. };
  66709. Skeleton.prototype.sortBones = function () {
  66710. var bones = new Array();
  66711. var visited = new Array(this.bones.length);
  66712. for (var index = 0; index < this.bones.length; index++) {
  66713. this._sortBones(index, bones, visited);
  66714. }
  66715. this.bones = bones;
  66716. };
  66717. Skeleton.prototype._sortBones = function (index, bones, visited) {
  66718. if (visited[index]) {
  66719. return;
  66720. }
  66721. visited[index] = true;
  66722. var bone = this.bones[index];
  66723. if (bone._index === undefined) {
  66724. bone._index = index;
  66725. }
  66726. var parentBone = bone.getParent();
  66727. if (parentBone) {
  66728. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  66729. }
  66730. bones.push(bone);
  66731. };
  66732. return Skeleton;
  66733. }());
  66734. BABYLON.Skeleton = Skeleton;
  66735. })(BABYLON || (BABYLON = {}));
  66736. //# sourceMappingURL=babylon.skeleton.js.map
  66737. var BABYLON;
  66738. (function (BABYLON) {
  66739. var SphericalPolynomial = /** @class */ (function () {
  66740. function SphericalPolynomial() {
  66741. this.x = BABYLON.Vector3.Zero();
  66742. this.y = BABYLON.Vector3.Zero();
  66743. this.z = BABYLON.Vector3.Zero();
  66744. this.xx = BABYLON.Vector3.Zero();
  66745. this.yy = BABYLON.Vector3.Zero();
  66746. this.zz = BABYLON.Vector3.Zero();
  66747. this.xy = BABYLON.Vector3.Zero();
  66748. this.yz = BABYLON.Vector3.Zero();
  66749. this.zx = BABYLON.Vector3.Zero();
  66750. }
  66751. SphericalPolynomial.prototype.addAmbient = function (color) {
  66752. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66753. this.xx = this.xx.add(colorVector);
  66754. this.yy = this.yy.add(colorVector);
  66755. this.zz = this.zz.add(colorVector);
  66756. };
  66757. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  66758. var result = new SphericalPolynomial();
  66759. result.x = harmonics.L11.scale(1.02333);
  66760. result.y = harmonics.L1_1.scale(1.02333);
  66761. result.z = harmonics.L10.scale(1.02333);
  66762. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  66763. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  66764. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  66765. result.yz = harmonics.L2_1.scale(0.858086);
  66766. result.zx = harmonics.L21.scale(0.858086);
  66767. result.xy = harmonics.L2_2.scale(0.858086);
  66768. result.scale(1.0 / Math.PI);
  66769. return result;
  66770. };
  66771. SphericalPolynomial.prototype.scale = function (scale) {
  66772. this.x = this.x.scale(scale);
  66773. this.y = this.y.scale(scale);
  66774. this.z = this.z.scale(scale);
  66775. this.xx = this.xx.scale(scale);
  66776. this.yy = this.yy.scale(scale);
  66777. this.zz = this.zz.scale(scale);
  66778. this.yz = this.yz.scale(scale);
  66779. this.zx = this.zx.scale(scale);
  66780. this.xy = this.xy.scale(scale);
  66781. };
  66782. return SphericalPolynomial;
  66783. }());
  66784. BABYLON.SphericalPolynomial = SphericalPolynomial;
  66785. var SphericalHarmonics = /** @class */ (function () {
  66786. function SphericalHarmonics() {
  66787. this.L00 = BABYLON.Vector3.Zero();
  66788. this.L1_1 = BABYLON.Vector3.Zero();
  66789. this.L10 = BABYLON.Vector3.Zero();
  66790. this.L11 = BABYLON.Vector3.Zero();
  66791. this.L2_2 = BABYLON.Vector3.Zero();
  66792. this.L2_1 = BABYLON.Vector3.Zero();
  66793. this.L20 = BABYLON.Vector3.Zero();
  66794. this.L21 = BABYLON.Vector3.Zero();
  66795. this.L22 = BABYLON.Vector3.Zero();
  66796. }
  66797. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  66798. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66799. var c = colorVector.scale(deltaSolidAngle);
  66800. this.L00 = this.L00.add(c.scale(0.282095));
  66801. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  66802. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  66803. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  66804. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  66805. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  66806. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  66807. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  66808. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  66809. };
  66810. SphericalHarmonics.prototype.scale = function (scale) {
  66811. this.L00 = this.L00.scale(scale);
  66812. this.L1_1 = this.L1_1.scale(scale);
  66813. this.L10 = this.L10.scale(scale);
  66814. this.L11 = this.L11.scale(scale);
  66815. this.L2_2 = this.L2_2.scale(scale);
  66816. this.L2_1 = this.L2_1.scale(scale);
  66817. this.L20 = this.L20.scale(scale);
  66818. this.L21 = this.L21.scale(scale);
  66819. this.L22 = this.L22.scale(scale);
  66820. };
  66821. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  66822. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  66823. //
  66824. // E_lm = A_l * L_lm
  66825. //
  66826. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  66827. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  66828. // the scaling factors are given in equation 9.
  66829. // Constant (Band 0)
  66830. this.L00 = this.L00.scale(3.141593);
  66831. // Linear (Band 1)
  66832. this.L1_1 = this.L1_1.scale(2.094395);
  66833. this.L10 = this.L10.scale(2.094395);
  66834. this.L11 = this.L11.scale(2.094395);
  66835. // Quadratic (Band 2)
  66836. this.L2_2 = this.L2_2.scale(0.785398);
  66837. this.L2_1 = this.L2_1.scale(0.785398);
  66838. this.L20 = this.L20.scale(0.785398);
  66839. this.L21 = this.L21.scale(0.785398);
  66840. this.L22 = this.L22.scale(0.785398);
  66841. };
  66842. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  66843. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  66844. // L = (1/pi) * E * rho
  66845. //
  66846. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  66847. this.scale(1.0 / Math.PI);
  66848. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  66849. // (The pixel shader must apply albedo after texture fetches, etc).
  66850. };
  66851. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  66852. var result = new SphericalHarmonics();
  66853. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  66854. result.L1_1 = polynomial.y.scale(0.977204);
  66855. result.L10 = polynomial.z.scale(0.977204);
  66856. result.L11 = polynomial.x.scale(0.977204);
  66857. result.L2_2 = polynomial.xy.scale(1.16538);
  66858. result.L2_1 = polynomial.yz.scale(1.16538);
  66859. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  66860. result.L21 = polynomial.zx.scale(1.16538);
  66861. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  66862. result.scale(Math.PI);
  66863. return result;
  66864. };
  66865. return SphericalHarmonics;
  66866. }());
  66867. BABYLON.SphericalHarmonics = SphericalHarmonics;
  66868. })(BABYLON || (BABYLON = {}));
  66869. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  66870. var BABYLON;
  66871. (function (BABYLON) {
  66872. var FileFaceOrientation = /** @class */ (function () {
  66873. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  66874. this.name = name;
  66875. this.worldAxisForNormal = worldAxisForNormal;
  66876. this.worldAxisForFileX = worldAxisForFileX;
  66877. this.worldAxisForFileY = worldAxisForFileY;
  66878. }
  66879. return FileFaceOrientation;
  66880. }());
  66881. ;
  66882. /**
  66883. * Helper class dealing with the extraction of spherical polynomial dataArray
  66884. * from a cube map.
  66885. */
  66886. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  66887. function CubeMapToSphericalPolynomialTools() {
  66888. }
  66889. /**
  66890. * Converts a texture to the according Spherical Polynomial data.
  66891. * This extracts the first 3 orders only as they are the only one used in the lighting.
  66892. *
  66893. * @param texture The texture to extract the information from.
  66894. * @return The Spherical Polynomial data.
  66895. */
  66896. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  66897. if (!texture.isCube) {
  66898. // Only supports cube Textures currently.
  66899. return null;
  66900. }
  66901. var size = texture.getSize().width;
  66902. var right = texture.readPixels(0);
  66903. var left = texture.readPixels(1);
  66904. var up;
  66905. var down;
  66906. if (texture.isRenderTarget) {
  66907. up = texture.readPixels(3);
  66908. down = texture.readPixels(2);
  66909. }
  66910. else {
  66911. up = texture.readPixels(2);
  66912. down = texture.readPixels(3);
  66913. }
  66914. var front = texture.readPixels(4);
  66915. var back = texture.readPixels(5);
  66916. var gammaSpace = texture.gammaSpace;
  66917. // Always read as RGBA.
  66918. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  66919. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66920. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66921. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66922. }
  66923. var cubeInfo = {
  66924. size: size,
  66925. right: right,
  66926. left: left,
  66927. up: up,
  66928. down: down,
  66929. front: front,
  66930. back: back,
  66931. format: format,
  66932. type: type,
  66933. gammaSpace: gammaSpace,
  66934. };
  66935. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  66936. };
  66937. /**
  66938. * Converts a cubemap to the according Spherical Polynomial data.
  66939. * This extracts the first 3 orders only as they are the only one used in the lighting.
  66940. *
  66941. * @param cubeInfo The Cube map to extract the information from.
  66942. * @return The Spherical Polynomial data.
  66943. */
  66944. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  66945. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  66946. var totalSolidAngle = 0.0;
  66947. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  66948. var du = 2.0 / cubeInfo.size;
  66949. var dv = du;
  66950. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  66951. var minUV = du * 0.5 - 1.0;
  66952. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  66953. var fileFace = this.FileFaces[faceIndex];
  66954. var dataArray = cubeInfo[fileFace.name];
  66955. var v = minUV;
  66956. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  66957. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  66958. // Because SP is still linear, so summation is fine in that basis.
  66959. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  66960. for (var y = 0; y < cubeInfo.size; y++) {
  66961. var u = minUV;
  66962. for (var x = 0; x < cubeInfo.size; x++) {
  66963. // World direction (not normalised)
  66964. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  66965. worldDirection.normalize();
  66966. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  66967. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  66968. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  66969. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  66970. // Handle Integer types.
  66971. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66972. r /= 255;
  66973. g /= 255;
  66974. b /= 255;
  66975. }
  66976. // Handle Gamma space textures.
  66977. if (cubeInfo.gammaSpace) {
  66978. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  66979. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  66980. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  66981. }
  66982. var color = new BABYLON.Color3(r, g, b);
  66983. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  66984. totalSolidAngle += deltaSolidAngle;
  66985. u += du;
  66986. }
  66987. v += dv;
  66988. }
  66989. }
  66990. // Solid angle for entire sphere is 4*pi
  66991. var sphereSolidAngle = 4.0 * Math.PI;
  66992. // Adjust the solid angle to allow for how many faces we processed.
  66993. var facesProcessed = 6.0;
  66994. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  66995. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  66996. // This is needed because the numerical integration over the cube uses a
  66997. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  66998. // and also to compensate for accumulative error due to float precision in the summation.
  66999. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67000. sphericalHarmonics.scale(correctionFactor);
  67001. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67002. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67003. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67004. };
  67005. CubeMapToSphericalPolynomialTools.FileFaces = [
  67006. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67007. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67008. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67009. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67010. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67011. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67012. ];
  67013. return CubeMapToSphericalPolynomialTools;
  67014. }());
  67015. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67016. })(BABYLON || (BABYLON = {}));
  67017. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67018. var BABYLON;
  67019. (function (BABYLON) {
  67020. /**
  67021. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67022. */
  67023. var PanoramaToCubeMapTools = /** @class */ (function () {
  67024. function PanoramaToCubeMapTools() {
  67025. }
  67026. /**
  67027. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67028. *
  67029. * @param float32Array The source data.
  67030. * @param inputWidth The width of the input panorama.
  67031. * @param inputhHeight The height of the input panorama.
  67032. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67033. * @return The cubemap data
  67034. */
  67035. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67036. if (!float32Array) {
  67037. throw "ConvertPanoramaToCubemap: input cannot be null";
  67038. }
  67039. if (float32Array.length != inputWidth * inputHeight * 3) {
  67040. throw "ConvertPanoramaToCubemap: input size is wrong";
  67041. }
  67042. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67043. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67044. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67045. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67046. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67047. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67048. return {
  67049. front: textureFront,
  67050. back: textureBack,
  67051. left: textureLeft,
  67052. right: textureRight,
  67053. up: textureUp,
  67054. down: textureDown,
  67055. size: size,
  67056. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67057. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67058. gammaSpace: false,
  67059. };
  67060. };
  67061. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67062. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67063. var textureArray = new Float32Array(buffer);
  67064. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67065. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67066. var dy = 1 / texSize;
  67067. var fy = 0;
  67068. for (var y = 0; y < texSize; y++) {
  67069. var xv1 = faceData[0];
  67070. var xv2 = faceData[2];
  67071. for (var x = 0; x < texSize; x++) {
  67072. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67073. v.normalize();
  67074. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67075. // 3 channels per pixels
  67076. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67077. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67078. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67079. xv1 = xv1.add(rotDX1);
  67080. xv2 = xv2.add(rotDX2);
  67081. }
  67082. fy += dy;
  67083. }
  67084. return textureArray;
  67085. };
  67086. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67087. var theta = Math.atan2(vDir.z, vDir.x);
  67088. var phi = Math.acos(vDir.y);
  67089. while (theta < -Math.PI)
  67090. theta += 2 * Math.PI;
  67091. while (theta > Math.PI)
  67092. theta -= 2 * Math.PI;
  67093. var dx = theta / Math.PI;
  67094. var dy = phi / Math.PI;
  67095. // recenter.
  67096. dx = dx * 0.5 + 0.5;
  67097. var px = Math.round(dx * inputWidth);
  67098. if (px < 0)
  67099. px = 0;
  67100. else if (px >= inputWidth)
  67101. px = inputWidth - 1;
  67102. var py = Math.round(dy * inputHeight);
  67103. if (py < 0)
  67104. py = 0;
  67105. else if (py >= inputHeight)
  67106. py = inputHeight - 1;
  67107. var inputY = (inputHeight - py - 1);
  67108. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67109. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67110. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67111. return {
  67112. r: r,
  67113. g: g,
  67114. b: b
  67115. };
  67116. };
  67117. PanoramaToCubeMapTools.FACE_FRONT = [
  67118. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67119. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67120. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67121. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67122. ];
  67123. PanoramaToCubeMapTools.FACE_BACK = [
  67124. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67125. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67126. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67127. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67128. ];
  67129. PanoramaToCubeMapTools.FACE_RIGHT = [
  67130. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67131. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67132. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67133. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67134. ];
  67135. PanoramaToCubeMapTools.FACE_LEFT = [
  67136. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67137. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67138. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67139. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67140. ];
  67141. PanoramaToCubeMapTools.FACE_DOWN = [
  67142. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67143. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67144. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67145. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67146. ];
  67147. PanoramaToCubeMapTools.FACE_UP = [
  67148. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67149. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67150. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67151. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67152. ];
  67153. return PanoramaToCubeMapTools;
  67154. }());
  67155. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67156. })(BABYLON || (BABYLON = {}));
  67157. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67158. var BABYLON;
  67159. (function (BABYLON) {
  67160. ;
  67161. /**
  67162. * This groups tools to convert HDR texture to native colors array.
  67163. */
  67164. var HDRTools = /** @class */ (function () {
  67165. function HDRTools() {
  67166. }
  67167. HDRTools.Ldexp = function (mantissa, exponent) {
  67168. if (exponent > 1023) {
  67169. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67170. }
  67171. if (exponent < -1074) {
  67172. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67173. }
  67174. return mantissa * Math.pow(2, exponent);
  67175. };
  67176. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67177. if (exponent > 0) {
  67178. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67179. float32array[index + 0] = red * exponent;
  67180. float32array[index + 1] = green * exponent;
  67181. float32array[index + 2] = blue * exponent;
  67182. }
  67183. else {
  67184. float32array[index + 0] = 0;
  67185. float32array[index + 1] = 0;
  67186. float32array[index + 2] = 0;
  67187. }
  67188. };
  67189. HDRTools.readStringLine = function (uint8array, startIndex) {
  67190. var line = "";
  67191. var character = "";
  67192. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67193. character = String.fromCharCode(uint8array[i]);
  67194. if (character == "\n") {
  67195. break;
  67196. }
  67197. line += character;
  67198. }
  67199. return line;
  67200. };
  67201. /**
  67202. * Reads header information from an RGBE texture stored in a native array.
  67203. * More information on this format are available here:
  67204. * https://en.wikipedia.org/wiki/RGBE_image_format
  67205. *
  67206. * @param uint8array The binary file stored in native array.
  67207. * @return The header information.
  67208. */
  67209. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67210. var height = 0;
  67211. var width = 0;
  67212. var line = this.readStringLine(uint8array, 0);
  67213. if (line[0] != '#' || line[1] != '?') {
  67214. throw "Bad HDR Format.";
  67215. }
  67216. var endOfHeader = false;
  67217. var findFormat = false;
  67218. var lineIndex = 0;
  67219. do {
  67220. lineIndex += (line.length + 1);
  67221. line = this.readStringLine(uint8array, lineIndex);
  67222. if (line == "FORMAT=32-bit_rle_rgbe") {
  67223. findFormat = true;
  67224. }
  67225. else if (line.length == 0) {
  67226. endOfHeader = true;
  67227. }
  67228. } while (!endOfHeader);
  67229. if (!findFormat) {
  67230. throw "HDR Bad header format, unsupported FORMAT";
  67231. }
  67232. lineIndex += (line.length + 1);
  67233. line = this.readStringLine(uint8array, lineIndex);
  67234. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67235. var match = sizeRegexp.exec(line);
  67236. // TODO. Support +Y and -X if needed.
  67237. if (!match || match.length < 3) {
  67238. throw "HDR Bad header format, no size";
  67239. }
  67240. width = parseInt(match[2]);
  67241. height = parseInt(match[1]);
  67242. if (width < 8 || width > 0x7fff) {
  67243. throw "HDR Bad header format, unsupported size";
  67244. }
  67245. lineIndex += (line.length + 1);
  67246. return {
  67247. height: height,
  67248. width: width,
  67249. dataPosition: lineIndex
  67250. };
  67251. };
  67252. /**
  67253. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67254. * This RGBE texture needs to store the information as a panorama.
  67255. *
  67256. * More information on this format are available here:
  67257. * https://en.wikipedia.org/wiki/RGBE_image_format
  67258. *
  67259. * @param buffer The binary file stored in an array buffer.
  67260. * @param size The expected size of the extracted cubemap.
  67261. * @return The Cube Map information.
  67262. */
  67263. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67264. var uint8array = new Uint8Array(buffer);
  67265. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67266. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67267. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67268. return cubeMapData;
  67269. };
  67270. /**
  67271. * Returns the pixels data extracted from an RGBE texture.
  67272. * This pixels will be stored left to right up to down in the R G B order in one array.
  67273. *
  67274. * More information on this format are available here:
  67275. * https://en.wikipedia.org/wiki/RGBE_image_format
  67276. *
  67277. * @param uint8array The binary file stored in an array buffer.
  67278. * @param hdrInfo The header information of the file.
  67279. * @return The pixels data in RGB right to left up to down order.
  67280. */
  67281. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67282. // Keep for multi format supports.
  67283. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67284. };
  67285. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67286. var num_scanlines = hdrInfo.height;
  67287. var scanline_width = hdrInfo.width;
  67288. var a, b, c, d, count;
  67289. var dataIndex = hdrInfo.dataPosition;
  67290. var index = 0, endIndex = 0, i = 0;
  67291. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67292. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67293. // 3 channels of 4 bytes per pixel in float.
  67294. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67295. var resultArray = new Float32Array(resultBuffer);
  67296. // read in each successive scanline
  67297. while (num_scanlines > 0) {
  67298. a = uint8array[dataIndex++];
  67299. b = uint8array[dataIndex++];
  67300. c = uint8array[dataIndex++];
  67301. d = uint8array[dataIndex++];
  67302. if (a != 2 || b != 2 || (c & 0x80)) {
  67303. // this file is not run length encoded
  67304. throw "HDR Bad header format, not RLE";
  67305. }
  67306. if (((c << 8) | d) != scanline_width) {
  67307. throw "HDR Bad header format, wrong scan line width";
  67308. }
  67309. index = 0;
  67310. // read each of the four channels for the scanline into the buffer
  67311. for (i = 0; i < 4; i++) {
  67312. endIndex = (i + 1) * scanline_width;
  67313. while (index < endIndex) {
  67314. a = uint8array[dataIndex++];
  67315. b = uint8array[dataIndex++];
  67316. if (a > 128) {
  67317. // a run of the same value
  67318. count = a - 128;
  67319. if ((count == 0) || (count > endIndex - index)) {
  67320. throw "HDR Bad Format, bad scanline data (run)";
  67321. }
  67322. while (count-- > 0) {
  67323. scanLineArray[index++] = b;
  67324. }
  67325. }
  67326. else {
  67327. // a non-run
  67328. count = a;
  67329. if ((count == 0) || (count > endIndex - index)) {
  67330. throw "HDR Bad Format, bad scanline data (non-run)";
  67331. }
  67332. scanLineArray[index++] = b;
  67333. if (--count > 0) {
  67334. for (var j = 0; j < count; j++) {
  67335. scanLineArray[index++] = uint8array[dataIndex++];
  67336. }
  67337. }
  67338. }
  67339. }
  67340. }
  67341. // now convert data from buffer into floats
  67342. for (i = 0; i < scanline_width; i++) {
  67343. a = scanLineArray[i];
  67344. b = scanLineArray[i + scanline_width];
  67345. c = scanLineArray[i + 2 * scanline_width];
  67346. d = scanLineArray[i + 3 * scanline_width];
  67347. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67348. }
  67349. num_scanlines--;
  67350. }
  67351. return resultArray;
  67352. };
  67353. return HDRTools;
  67354. }());
  67355. BABYLON.HDRTools = HDRTools;
  67356. })(BABYLON || (BABYLON = {}));
  67357. //# sourceMappingURL=babylon.hdr.js.map
  67358. var BABYLON;
  67359. (function (BABYLON) {
  67360. /**
  67361. * This represents a texture coming from an HDR input.
  67362. *
  67363. * The only supported format is currently panorama picture stored in RGBE format.
  67364. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67365. */
  67366. var HDRCubeTexture = /** @class */ (function (_super) {
  67367. __extends(HDRCubeTexture, _super);
  67368. /**
  67369. * Instantiates an HDRTexture from the following parameters.
  67370. *
  67371. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67372. * @param scene The scene the texture will be used in
  67373. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  67374. * @param noMipmap Forces to not generate the mipmap if true
  67375. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67376. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  67377. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67378. */
  67379. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67380. if (noMipmap === void 0) { noMipmap = false; }
  67381. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67382. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67383. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67384. if (onLoad === void 0) { onLoad = null; }
  67385. if (onError === void 0) { onError = null; }
  67386. var _this = _super.call(this, scene) || this;
  67387. _this._useInGammaSpace = false;
  67388. _this._generateHarmonics = true;
  67389. _this._isBABYLONPreprocessed = false;
  67390. _this._onLoad = null;
  67391. _this._onError = null;
  67392. /**
  67393. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67394. */
  67395. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67396. /**
  67397. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67398. * This is usefull at run time to apply the good shader.
  67399. */
  67400. _this.isPMREM = false;
  67401. _this._isBlocking = true;
  67402. if (!url) {
  67403. return _this;
  67404. }
  67405. _this.name = url;
  67406. _this.url = url;
  67407. _this.hasAlpha = false;
  67408. _this.isCube = true;
  67409. _this._textureMatrix = BABYLON.Matrix.Identity();
  67410. _this._onLoad = onLoad;
  67411. _this._onError = onError;
  67412. _this.gammaSpace = false;
  67413. var caps = scene.getEngine().getCaps();
  67414. if (size) {
  67415. _this._isBABYLONPreprocessed = false;
  67416. _this._noMipmap = noMipmap;
  67417. _this._size = size;
  67418. _this._useInGammaSpace = useInGammaSpace;
  67419. _this._usePMREMGenerator = usePMREMGenerator &&
  67420. caps.textureLOD &&
  67421. caps.textureFloat &&
  67422. !_this._useInGammaSpace;
  67423. }
  67424. else {
  67425. _this._isBABYLONPreprocessed = true;
  67426. _this._noMipmap = false;
  67427. _this._useInGammaSpace = false;
  67428. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67429. !_this._useInGammaSpace;
  67430. }
  67431. _this.isPMREM = _this._usePMREMGenerator;
  67432. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67433. if (!_this._texture) {
  67434. if (!scene.useDelayedTextureLoading) {
  67435. _this.loadTexture();
  67436. }
  67437. else {
  67438. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67439. }
  67440. }
  67441. return _this;
  67442. }
  67443. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67444. /**
  67445. * Gets wether or not the texture is blocking during loading.
  67446. */
  67447. get: function () {
  67448. return this._isBlocking;
  67449. },
  67450. /**
  67451. * Sets wether or not the texture is blocking during loading.
  67452. */
  67453. set: function (value) {
  67454. this._isBlocking = value;
  67455. },
  67456. enumerable: true,
  67457. configurable: true
  67458. });
  67459. /**
  67460. * Occurs when the file is a preprocessed .babylon.hdr file.
  67461. */
  67462. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67463. var _this = this;
  67464. var mipLevels = 0;
  67465. var floatArrayView = null;
  67466. var scene = this.getScene();
  67467. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  67468. var mips = new Array();
  67469. if (!floatArrayView) {
  67470. return mips;
  67471. }
  67472. var startIndex = 30;
  67473. for (var level = 0; level < mipLevels; level++) {
  67474. mips.push([]);
  67475. // Fill each pixel of the mip level.
  67476. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  67477. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67478. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  67479. mips[level].push(faceData);
  67480. startIndex += faceSize;
  67481. }
  67482. }
  67483. return mips;
  67484. } : null;
  67485. var callback = function (buffer) {
  67486. var scene = _this.getScene();
  67487. if (!scene) {
  67488. return null;
  67489. }
  67490. // Create Native Array Views
  67491. var intArrayView = new Int32Array(buffer);
  67492. floatArrayView = new Float32Array(buffer);
  67493. // Fill header.
  67494. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  67495. _this._size = intArrayView[1]; // CubeMap max mip face size.
  67496. // Update Texture Information.
  67497. if (!_this._texture) {
  67498. return null;
  67499. }
  67500. _this._texture.updateSize(_this._size, _this._size);
  67501. // Fill polynomial information.
  67502. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  67503. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  67504. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  67505. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  67506. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  67507. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  67508. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  67509. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  67510. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  67511. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  67512. _this.sphericalPolynomial = sphericalPolynomial;
  67513. // Fill pixel data.
  67514. mipLevels = intArrayView[29]; // Number of mip levels.
  67515. var startIndex = 30;
  67516. var data = [];
  67517. var faceSize = Math.pow(_this._size, 2) * 3;
  67518. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67519. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  67520. startIndex += faceSize;
  67521. }
  67522. var results = [];
  67523. var byteArray = null;
  67524. // Push each faces.
  67525. for (var k = 0; k < 6; k++) {
  67526. var dataFace = null;
  67527. // To be deprecated.
  67528. if (version === 1) {
  67529. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  67530. dataFace = data[j];
  67531. }
  67532. // If special cases.
  67533. if (!mipmapGenerator && dataFace) {
  67534. if (!scene.getEngine().getCaps().textureFloat) {
  67535. // 3 channels of 1 bytes per pixel in bytes.
  67536. var byteBuffer = new ArrayBuffer(faceSize);
  67537. byteArray = new Uint8Array(byteBuffer);
  67538. }
  67539. for (var i = 0; i < _this._size * _this._size; i++) {
  67540. // Put in gamma space if requested.
  67541. if (_this._useInGammaSpace) {
  67542. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67543. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67544. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67545. }
  67546. // Convert to int texture for fallback.
  67547. if (byteArray) {
  67548. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67549. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67550. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67551. // May use luminance instead if the result is not accurate.
  67552. var max = Math.max(Math.max(r, g), b);
  67553. if (max > 255) {
  67554. var scale = 255 / max;
  67555. r *= scale;
  67556. g *= scale;
  67557. b *= scale;
  67558. }
  67559. byteArray[(i * 3) + 0] = r;
  67560. byteArray[(i * 3) + 1] = g;
  67561. byteArray[(i * 3) + 2] = b;
  67562. }
  67563. }
  67564. }
  67565. // Fill the array accordingly.
  67566. if (byteArray) {
  67567. results.push(byteArray);
  67568. }
  67569. else {
  67570. results.push(dataFace);
  67571. }
  67572. }
  67573. return results;
  67574. };
  67575. if (scene) {
  67576. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  67577. }
  67578. };
  67579. /**
  67580. * Occurs when the file is raw .hdr file.
  67581. */
  67582. HDRCubeTexture.prototype.loadHDRTexture = function () {
  67583. var _this = this;
  67584. var callback = function (buffer) {
  67585. var scene = _this.getScene();
  67586. if (!scene) {
  67587. return null;
  67588. }
  67589. // Extract the raw linear data.
  67590. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  67591. // Generate harmonics if needed.
  67592. if (_this._generateHarmonics) {
  67593. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  67594. _this.sphericalPolynomial = sphericalPolynomial;
  67595. }
  67596. var results = [];
  67597. var byteArray = null;
  67598. // Push each faces.
  67599. for (var j = 0; j < 6; j++) {
  67600. // Create uintarray fallback.
  67601. if (!scene.getEngine().getCaps().textureFloat) {
  67602. // 3 channels of 1 bytes per pixel in bytes.
  67603. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  67604. byteArray = new Uint8Array(byteBuffer);
  67605. }
  67606. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  67607. // If special cases.
  67608. if (_this._useInGammaSpace || byteArray) {
  67609. for (var i = 0; i < _this._size * _this._size; i++) {
  67610. // Put in gamma space if requested.
  67611. if (_this._useInGammaSpace) {
  67612. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67613. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67614. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67615. }
  67616. // Convert to int texture for fallback.
  67617. if (byteArray) {
  67618. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67619. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67620. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67621. // May use luminance instead if the result is not accurate.
  67622. var max = Math.max(Math.max(r, g), b);
  67623. if (max > 255) {
  67624. var scale = 255 / max;
  67625. r *= scale;
  67626. g *= scale;
  67627. b *= scale;
  67628. }
  67629. byteArray[(i * 3) + 0] = r;
  67630. byteArray[(i * 3) + 1] = g;
  67631. byteArray[(i * 3) + 2] = b;
  67632. }
  67633. }
  67634. }
  67635. if (byteArray) {
  67636. results.push(byteArray);
  67637. }
  67638. else {
  67639. results.push(dataFace);
  67640. }
  67641. }
  67642. return results;
  67643. };
  67644. var mipmapGenerator = null;
  67645. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  67646. // if (!this._noMipmap &&
  67647. // this._usePMREMGenerator) {
  67648. // mipmapGenerator = (data: ArrayBufferView[]) => {
  67649. // // Custom setup of the generator matching with the PBR shader values.
  67650. // var generator = new BABYLON.PMREMGenerator(data,
  67651. // this._size,
  67652. // this._size,
  67653. // 0,
  67654. // 3,
  67655. // this.getScene().getEngine().getCaps().textureFloat,
  67656. // 2048,
  67657. // 0.25,
  67658. // false,
  67659. // true);
  67660. // return generator.filterCubeMap();
  67661. // };
  67662. // }
  67663. var scene = this.getScene();
  67664. if (scene) {
  67665. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  67666. }
  67667. };
  67668. /**
  67669. * Starts the loading process of the texture.
  67670. */
  67671. HDRCubeTexture.prototype.loadTexture = function () {
  67672. if (this._isBABYLONPreprocessed) {
  67673. this.loadBabylonTexture();
  67674. }
  67675. else {
  67676. this.loadHDRTexture();
  67677. }
  67678. };
  67679. HDRCubeTexture.prototype.clone = function () {
  67680. var scene = this.getScene();
  67681. if (!scene) {
  67682. return this;
  67683. }
  67684. var size = (this._isBABYLONPreprocessed ? null : this._size);
  67685. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  67686. // Base texture
  67687. newTexture.level = this.level;
  67688. newTexture.wrapU = this.wrapU;
  67689. newTexture.wrapV = this.wrapV;
  67690. newTexture.coordinatesIndex = this.coordinatesIndex;
  67691. newTexture.coordinatesMode = this.coordinatesMode;
  67692. return newTexture;
  67693. };
  67694. // Methods
  67695. HDRCubeTexture.prototype.delayLoad = function () {
  67696. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67697. return;
  67698. }
  67699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67700. this._texture = this._getFromCache(this.url, this._noMipmap);
  67701. if (!this._texture) {
  67702. this.loadTexture();
  67703. }
  67704. };
  67705. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  67706. return this._textureMatrix;
  67707. };
  67708. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67709. this._textureMatrix = value;
  67710. };
  67711. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67712. var texture = null;
  67713. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  67714. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  67715. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  67716. texture.name = parsedTexture.name;
  67717. texture.hasAlpha = parsedTexture.hasAlpha;
  67718. texture.level = parsedTexture.level;
  67719. texture.coordinatesMode = parsedTexture.coordinatesMode;
  67720. texture.isBlocking = parsedTexture.isBlocking;
  67721. }
  67722. return texture;
  67723. };
  67724. HDRCubeTexture.prototype.serialize = function () {
  67725. if (!this.name) {
  67726. return null;
  67727. }
  67728. var serializationObject = {};
  67729. serializationObject.name = this.name;
  67730. serializationObject.hasAlpha = this.hasAlpha;
  67731. serializationObject.isCube = true;
  67732. serializationObject.level = this.level;
  67733. serializationObject.size = this._size;
  67734. serializationObject.coordinatesMode = this.coordinatesMode;
  67735. serializationObject.useInGammaSpace = this._useInGammaSpace;
  67736. serializationObject.generateHarmonics = this._generateHarmonics;
  67737. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  67738. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  67739. serializationObject.customType = "BABYLON.HDRCubeTexture";
  67740. serializationObject.noMipmap = this._noMipmap;
  67741. serializationObject.isBlocking = this._isBlocking;
  67742. return serializationObject;
  67743. };
  67744. /**
  67745. * Saves as a file the data contained in the texture in a binary format.
  67746. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67747. * as the spherical used in the lighting.
  67748. * @param url The HDR file url.
  67749. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67750. * @param onError Method called if any error happens during download.
  67751. * @return The packed binary data.
  67752. */
  67753. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  67754. if (onError === void 0) { onError = null; }
  67755. var callback = function (buffer) {
  67756. var data = new Blob([buffer], { type: 'application/octet-stream' });
  67757. // Returns a URL you can use as a href.
  67758. var objUrl = window.URL.createObjectURL(data);
  67759. // Simulates a link to it and click to dowload.
  67760. var a = document.createElement("a");
  67761. document.body.appendChild(a);
  67762. a.style.display = "none";
  67763. a.href = objUrl;
  67764. a.download = "envmap.babylon.hdr";
  67765. a.click();
  67766. };
  67767. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  67768. };
  67769. /**
  67770. * Serializes the data contained in the texture in a binary format.
  67771. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67772. * as the spherical used in the lighting.
  67773. * @param url The HDR file url.
  67774. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67775. * @param onError Method called if any error happens during download.
  67776. * @return The packed binary data.
  67777. */
  67778. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  67779. if (onError === void 0) { onError = null; }
  67780. // Needs the url tho create the texture.
  67781. if (!url) {
  67782. return;
  67783. }
  67784. // Check Power of two size.
  67785. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  67786. return;
  67787. }
  67788. // Coming Back in 3.x.
  67789. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  67790. };
  67791. HDRCubeTexture._facesMapping = [
  67792. "right",
  67793. "left",
  67794. "up",
  67795. "down",
  67796. "front",
  67797. "back"
  67798. ];
  67799. return HDRCubeTexture;
  67800. }(BABYLON.BaseTexture));
  67801. BABYLON.HDRCubeTexture = HDRCubeTexture;
  67802. })(BABYLON || (BABYLON = {}));
  67803. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  67804. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  67805. // Huge respect for a such great lib.
  67806. // Earcut license:
  67807. // Copyright (c) 2016, Mapbox
  67808. //
  67809. // Permission to use, copy, modify, and/or distribute this software for any purpose
  67810. // with or without fee is hereby granted, provided that the above copyright notice
  67811. // and this permission notice appear in all copies.
  67812. //
  67813. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  67814. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  67815. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  67816. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  67817. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  67818. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  67819. // THIS SOFTWARE.
  67820. var Earcut;
  67821. (function (Earcut) {
  67822. /**
  67823. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  67824. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  67825. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  67826. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  67827. */
  67828. function earcut(data, holeIndices, dim) {
  67829. dim = dim || 2;
  67830. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  67831. if (!outerNode)
  67832. return triangles;
  67833. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  67834. if (hasHoles)
  67835. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  67836. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  67837. if (data.length > 80 * dim) {
  67838. minX = maxX = data[0];
  67839. minY = maxY = data[1];
  67840. for (var i = dim; i < outerLen; i += dim) {
  67841. x = data[i];
  67842. y = data[i + 1];
  67843. if (x < minX)
  67844. minX = x;
  67845. if (y < minY)
  67846. minY = y;
  67847. if (x > maxX)
  67848. maxX = x;
  67849. if (y > maxY)
  67850. maxY = y;
  67851. }
  67852. // minX, minY and size are later used to transform coords into integers for z-order calculation
  67853. size = Math.max(maxX - minX, maxY - minY);
  67854. }
  67855. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  67856. return triangles;
  67857. }
  67858. Earcut.earcut = earcut;
  67859. var Node = /** @class */ (function () {
  67860. function Node(i, x, y) {
  67861. this.i = i;
  67862. this.x = x;
  67863. this.y = y;
  67864. this.prev = null;
  67865. this.next = null;
  67866. this.z = null;
  67867. this.prevZ = null;
  67868. this.nextZ = null;
  67869. this.steiner = false;
  67870. }
  67871. return Node;
  67872. }());
  67873. // create a circular doubly linked list from polygon points in the specified winding order
  67874. function linkedList(data, start, end, dim, clockwise) {
  67875. var i, last = null;
  67876. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  67877. for (i = start; i < end; i += dim)
  67878. last = insertNode(i, data[i], data[i + 1], last);
  67879. }
  67880. else {
  67881. for (i = end - dim; i >= start; i -= dim)
  67882. last = insertNode(i, data[i], data[i + 1], last);
  67883. }
  67884. if (last && equals(last, last.next)) {
  67885. removeNode(last);
  67886. last = last.next;
  67887. }
  67888. return last;
  67889. }
  67890. // eliminate colinear or duplicate points
  67891. function filterPoints(start, end) {
  67892. if (!start)
  67893. return start;
  67894. if (!end)
  67895. end = start;
  67896. var p = start, again;
  67897. do {
  67898. again = false;
  67899. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  67900. removeNode(p);
  67901. p = end = p.prev;
  67902. if (p === p.next)
  67903. return undefined;
  67904. again = true;
  67905. }
  67906. else {
  67907. p = p.next;
  67908. }
  67909. } while (again || p !== end);
  67910. return end;
  67911. }
  67912. // main ear slicing loop which triangulates a polygon (given as a linked list)
  67913. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  67914. if (!ear)
  67915. return;
  67916. // interlink polygon nodes in z-order
  67917. if (!pass && size)
  67918. indexCurve(ear, minX, minY, size);
  67919. var stop = ear, prev, next;
  67920. // iterate through ears, slicing them one by one
  67921. while (ear.prev !== ear.next) {
  67922. prev = ear.prev;
  67923. next = ear.next;
  67924. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  67925. // cut off the triangle
  67926. triangles.push(prev.i / dim);
  67927. triangles.push(ear.i / dim);
  67928. triangles.push(next.i / dim);
  67929. removeNode(ear);
  67930. // skipping the next vertice leads to less sliver triangles
  67931. ear = next.next;
  67932. stop = next.next;
  67933. continue;
  67934. }
  67935. ear = next;
  67936. // if we looped through the whole remaining polygon and can't find any more ears
  67937. if (ear === stop) {
  67938. // try filtering points and slicing again
  67939. if (!pass) {
  67940. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  67941. // if this didn't work, try curing all small self-intersections locally
  67942. }
  67943. else if (pass === 1) {
  67944. ear = cureLocalIntersections(ear, triangles, dim);
  67945. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  67946. // as a last resort, try splitting the remaining polygon into two
  67947. }
  67948. else if (pass === 2) {
  67949. splitEarcut(ear, triangles, dim, minX, minY, size);
  67950. }
  67951. break;
  67952. }
  67953. }
  67954. }
  67955. // check whether a polygon node forms a valid ear with adjacent nodes
  67956. function isEar(ear) {
  67957. var a = ear.prev, b = ear, c = ear.next;
  67958. if (area(a, b, c) >= 0)
  67959. return false; // reflex, can't be an ear
  67960. // now make sure we don't have other points inside the potential ear
  67961. var p = ear.next.next;
  67962. while (p !== ear.prev) {
  67963. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67964. area(p.prev, p, p.next) >= 0)
  67965. return false;
  67966. p = p.next;
  67967. }
  67968. return true;
  67969. }
  67970. function isEarHashed(ear, minX, minY, size) {
  67971. var a = ear.prev, b = ear, c = ear.next;
  67972. if (area(a, b, c) >= 0)
  67973. return false; // reflex, can't be an ear
  67974. // triangle bbox; min & max are calculated like this for speed
  67975. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  67976. // z-order range for the current triangle bbox;
  67977. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  67978. // first look for points inside the triangle in increasing z-order
  67979. var p = ear.nextZ;
  67980. while (p && p.z <= maxZ) {
  67981. if (p !== ear.prev &&
  67982. p !== ear.next &&
  67983. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67984. area(p.prev, p, p.next) >= 0)
  67985. return false;
  67986. p = p.nextZ;
  67987. }
  67988. // then look for points in decreasing z-order
  67989. p = ear.prevZ;
  67990. while (p && p.z >= minZ) {
  67991. if (p !== ear.prev &&
  67992. p !== ear.next &&
  67993. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67994. area(p.prev, p, p.next) >= 0)
  67995. return false;
  67996. p = p.prevZ;
  67997. }
  67998. return true;
  67999. }
  68000. // go through all polygon nodes and cure small local self-intersections
  68001. function cureLocalIntersections(start, triangles, dim) {
  68002. var p = start;
  68003. do {
  68004. var a = p.prev, b = p.next.next;
  68005. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68006. triangles.push(a.i / dim);
  68007. triangles.push(p.i / dim);
  68008. triangles.push(b.i / dim);
  68009. // remove two nodes involved
  68010. removeNode(p);
  68011. removeNode(p.next);
  68012. p = start = b;
  68013. }
  68014. p = p.next;
  68015. } while (p !== start);
  68016. return p;
  68017. }
  68018. // try splitting polygon into two and triangulate them independently
  68019. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68020. // look for a valid diagonal that divides the polygon into two
  68021. var a = start;
  68022. do {
  68023. var b = a.next.next;
  68024. while (b !== a.prev) {
  68025. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68026. // split the polygon in two by the diagonal
  68027. var c = splitPolygon(a, b);
  68028. // filter colinear points around the cuts
  68029. a = filterPoints(a, a.next);
  68030. c = filterPoints(c, c.next);
  68031. // run earcut on each half
  68032. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68033. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68034. return;
  68035. }
  68036. b = b.next;
  68037. }
  68038. a = a.next;
  68039. } while (a !== start);
  68040. }
  68041. // link every hole into the outer loop, producing a single-ring polygon without holes
  68042. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68043. var queue = [], i, len, start, end, list;
  68044. for (i = 0, len = holeIndices.length; i < len; i++) {
  68045. start = holeIndices[i] * dim;
  68046. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68047. list = linkedList(data, start, end, dim, false);
  68048. if (list === list.next)
  68049. list.steiner = true;
  68050. queue.push(getLeftmost(list));
  68051. }
  68052. queue.sort(compareX);
  68053. // process holes from left to right
  68054. for (i = 0; i < queue.length; i++) {
  68055. eliminateHole(queue[i], outerNode);
  68056. outerNode = filterPoints(outerNode, outerNode.next);
  68057. }
  68058. return outerNode;
  68059. }
  68060. function compareX(a, b) {
  68061. return a.x - b.x;
  68062. }
  68063. // find a bridge between vertices that connects hole with an outer ring and and link it
  68064. function eliminateHole(hole, outerNode) {
  68065. outerNode = findHoleBridge(hole, outerNode);
  68066. if (outerNode) {
  68067. var b = splitPolygon(outerNode, hole);
  68068. filterPoints(b, b.next);
  68069. }
  68070. }
  68071. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68072. function findHoleBridge(hole, outerNode) {
  68073. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68074. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68075. // segment's endpoint with lesser x will be potential connection point
  68076. do {
  68077. if (hy <= p.y && hy >= p.next.y) {
  68078. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68079. if (x <= hx && x > qx) {
  68080. qx = x;
  68081. if (x === hx) {
  68082. if (hy === p.y)
  68083. return p;
  68084. if (hy === p.next.y)
  68085. return p.next;
  68086. }
  68087. m = p.x < p.next.x ? p : p.next;
  68088. }
  68089. }
  68090. p = p.next;
  68091. } while (p !== outerNode);
  68092. if (!m)
  68093. return null;
  68094. if (hx === qx)
  68095. return m.prev; // hole touches outer segment; pick lower endpoint
  68096. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68097. // if there are no points found, we have a valid connection;
  68098. // otherwise choose the point of the minimum angle with the ray as connection point
  68099. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68100. p = m.next;
  68101. while (p !== stop) {
  68102. if (hx >= p.x &&
  68103. p.x >= mx &&
  68104. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68105. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68106. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68107. m = p;
  68108. tanMin = tan;
  68109. }
  68110. }
  68111. p = p.next;
  68112. }
  68113. return m;
  68114. }
  68115. // interlink polygon nodes in z-order
  68116. function indexCurve(start, minX, minY, size) {
  68117. var p = start;
  68118. do {
  68119. if (p.z === null)
  68120. p.z = zOrder(p.x, p.y, minX, minY, size);
  68121. p.prevZ = p.prev;
  68122. p.nextZ = p.next;
  68123. p = p.next;
  68124. } while (p !== start);
  68125. p.prevZ.nextZ = null;
  68126. p.prevZ = null;
  68127. sortLinked(p);
  68128. }
  68129. // Simon Tatham's linked list merge sort algorithm
  68130. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68131. function sortLinked(list) {
  68132. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68133. do {
  68134. p = list;
  68135. list = null;
  68136. tail = null;
  68137. numMerges = 0;
  68138. while (p) {
  68139. numMerges++;
  68140. q = p;
  68141. pSize = 0;
  68142. for (i = 0; i < inSize; i++) {
  68143. pSize++;
  68144. q = q.nextZ;
  68145. if (!q)
  68146. break;
  68147. }
  68148. qSize = inSize;
  68149. while (pSize > 0 || (qSize > 0 && q)) {
  68150. if (pSize === 0) {
  68151. e = q;
  68152. q = q.nextZ;
  68153. qSize--;
  68154. }
  68155. else if (qSize === 0 || !q) {
  68156. e = p;
  68157. p = p.nextZ;
  68158. pSize--;
  68159. }
  68160. else if (p.z <= q.z) {
  68161. e = p;
  68162. p = p.nextZ;
  68163. pSize--;
  68164. }
  68165. else {
  68166. e = q;
  68167. q = q.nextZ;
  68168. qSize--;
  68169. }
  68170. if (tail)
  68171. tail.nextZ = e;
  68172. else
  68173. list = e;
  68174. e.prevZ = tail;
  68175. tail = e;
  68176. }
  68177. p = q;
  68178. }
  68179. tail.nextZ = null;
  68180. inSize *= 2;
  68181. } while (numMerges > 1);
  68182. return list;
  68183. }
  68184. // z-order of a point given coords and size of the data bounding box
  68185. function zOrder(x, y, minX, minY, size) {
  68186. // coords are transformed into non-negative 15-bit integer range
  68187. x = 32767 * (x - minX) / size;
  68188. y = 32767 * (y - minY) / size;
  68189. x = (x | (x << 8)) & 0x00FF00FF;
  68190. x = (x | (x << 4)) & 0x0F0F0F0F;
  68191. x = (x | (x << 2)) & 0x33333333;
  68192. x = (x | (x << 1)) & 0x55555555;
  68193. y = (y | (y << 8)) & 0x00FF00FF;
  68194. y = (y | (y << 4)) & 0x0F0F0F0F;
  68195. y = (y | (y << 2)) & 0x33333333;
  68196. y = (y | (y << 1)) & 0x55555555;
  68197. return x | (y << 1);
  68198. }
  68199. // find the leftmost node of a polygon ring
  68200. function getLeftmost(start) {
  68201. var p = start, leftmost = start;
  68202. do {
  68203. if (p.x < leftmost.x)
  68204. leftmost = p;
  68205. p = p.next;
  68206. } while (p !== start);
  68207. return leftmost;
  68208. }
  68209. // check if a point lies within a convex triangle
  68210. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68211. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68212. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68213. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68214. }
  68215. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68216. function isValidDiagonal(a, b) {
  68217. return a.next.i !== b.i &&
  68218. a.prev.i !== b.i &&
  68219. !intersectsPolygon(a, b) &&
  68220. locallyInside(a, b) &&
  68221. locallyInside(b, a) &&
  68222. middleInside(a, b);
  68223. }
  68224. // signed area of a triangle
  68225. function area(p, q, r) {
  68226. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68227. }
  68228. // check if two points are equal
  68229. function equals(p1, p2) {
  68230. return p1.x === p2.x && p1.y === p2.y;
  68231. }
  68232. // check if two segments intersect
  68233. function intersects(p1, q1, p2, q2) {
  68234. if ((equals(p1, q1) && equals(p2, q2)) ||
  68235. (equals(p1, q2) && equals(p2, q1)))
  68236. return true;
  68237. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68238. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68239. }
  68240. // check if a polygon diagonal intersects any polygon segments
  68241. function intersectsPolygon(a, b) {
  68242. var p = a;
  68243. do {
  68244. if (p.i !== a.i &&
  68245. p.next.i !== a.i &&
  68246. p.i !== b.i &&
  68247. p.next.i !== b.i &&
  68248. intersects(p, p.next, a, b))
  68249. return true;
  68250. p = p.next;
  68251. } while (p !== a);
  68252. return false;
  68253. }
  68254. // check if a polygon diagonal is locally inside the polygon
  68255. function locallyInside(a, b) {
  68256. return area(a.prev, a, a.next) < 0
  68257. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68258. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68259. }
  68260. // check if the middle point of a polygon diagonal is inside the polygon
  68261. function middleInside(a, b) {
  68262. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68263. do {
  68264. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68265. inside = !inside;
  68266. p = p.next;
  68267. } while (p !== a);
  68268. return inside;
  68269. }
  68270. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68271. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68272. function splitPolygon(a, b) {
  68273. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  68274. a.next = b;
  68275. b.prev = a;
  68276. a2.next = an;
  68277. an.prev = a2;
  68278. b2.next = a2;
  68279. a2.prev = b2;
  68280. bp.next = b2;
  68281. b2.prev = bp;
  68282. return b2;
  68283. }
  68284. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68285. function insertNode(i, x, y, last) {
  68286. var p = new Node(i, x, y);
  68287. if (!last) {
  68288. p.prev = p;
  68289. p.next = p;
  68290. }
  68291. else {
  68292. p.next = last.next;
  68293. p.prev = last;
  68294. last.next.prev = p;
  68295. last.next = p;
  68296. }
  68297. return p;
  68298. }
  68299. function removeNode(p) {
  68300. p.next.prev = p.prev;
  68301. p.prev.next = p.next;
  68302. if (p.prevZ)
  68303. p.prevZ.nextZ = p.nextZ;
  68304. if (p.nextZ)
  68305. p.nextZ.prevZ = p.prevZ;
  68306. }
  68307. /**
  68308. * return a percentage difference between the polygon area and its triangulation area;
  68309. * used to verify correctness of triangulation
  68310. */
  68311. function deviation(data, holeIndices, dim, triangles) {
  68312. var hasHoles = holeIndices && holeIndices.length;
  68313. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68314. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68315. if (hasHoles) {
  68316. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68317. var start = holeIndices[i] * dim;
  68318. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68319. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68320. }
  68321. }
  68322. var trianglesArea = 0;
  68323. for (i = 0; i < triangles.length; i += 3) {
  68324. var a = triangles[i] * dim;
  68325. var b = triangles[i + 1] * dim;
  68326. var c = triangles[i + 2] * dim;
  68327. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68328. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68329. }
  68330. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68331. }
  68332. Earcut.deviation = deviation;
  68333. ;
  68334. function signedArea(data, start, end, dim) {
  68335. var sum = 0;
  68336. for (var i = start, j = end - dim; i < end; i += dim) {
  68337. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68338. j = i;
  68339. }
  68340. return sum;
  68341. }
  68342. /**
  68343. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68344. */
  68345. function flatten(data) {
  68346. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68347. for (var i = 0; i < data.length; i++) {
  68348. for (var j = 0; j < data[i].length; j++) {
  68349. for (var d = 0; d < dim; d++)
  68350. result.vertices.push(data[i][j][d]);
  68351. }
  68352. if (i > 0) {
  68353. holeIndex += data[i - 1].length;
  68354. result.holes.push(holeIndex);
  68355. }
  68356. }
  68357. return result;
  68358. }
  68359. Earcut.flatten = flatten;
  68360. ;
  68361. })(Earcut || (Earcut = {}));
  68362. //# sourceMappingURL=babylon.earcut.js.map
  68363. var BABYLON;
  68364. (function (BABYLON) {
  68365. var IndexedVector2 = /** @class */ (function (_super) {
  68366. __extends(IndexedVector2, _super);
  68367. function IndexedVector2(original, index) {
  68368. var _this = _super.call(this, original.x, original.y) || this;
  68369. _this.index = index;
  68370. return _this;
  68371. }
  68372. return IndexedVector2;
  68373. }(BABYLON.Vector2));
  68374. var PolygonPoints = /** @class */ (function () {
  68375. function PolygonPoints() {
  68376. this.elements = new Array();
  68377. }
  68378. PolygonPoints.prototype.add = function (originalPoints) {
  68379. var _this = this;
  68380. var result = new Array();
  68381. originalPoints.forEach(function (point) {
  68382. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68383. var newPoint = new IndexedVector2(point, _this.elements.length);
  68384. result.push(newPoint);
  68385. _this.elements.push(newPoint);
  68386. }
  68387. });
  68388. return result;
  68389. };
  68390. PolygonPoints.prototype.computeBounds = function () {
  68391. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68392. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68393. this.elements.forEach(function (point) {
  68394. // x
  68395. if (point.x < lmin.x) {
  68396. lmin.x = point.x;
  68397. }
  68398. else if (point.x > lmax.x) {
  68399. lmax.x = point.x;
  68400. }
  68401. // y
  68402. if (point.y < lmin.y) {
  68403. lmin.y = point.y;
  68404. }
  68405. else if (point.y > lmax.y) {
  68406. lmax.y = point.y;
  68407. }
  68408. });
  68409. return {
  68410. min: lmin,
  68411. max: lmax,
  68412. width: lmax.x - lmin.x,
  68413. height: lmax.y - lmin.y
  68414. };
  68415. };
  68416. return PolygonPoints;
  68417. }());
  68418. var Polygon = /** @class */ (function () {
  68419. function Polygon() {
  68420. }
  68421. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68422. return [
  68423. new BABYLON.Vector2(xmin, ymin),
  68424. new BABYLON.Vector2(xmax, ymin),
  68425. new BABYLON.Vector2(xmax, ymax),
  68426. new BABYLON.Vector2(xmin, ymax)
  68427. ];
  68428. };
  68429. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68430. if (cx === void 0) { cx = 0; }
  68431. if (cy === void 0) { cy = 0; }
  68432. if (numberOfSides === void 0) { numberOfSides = 32; }
  68433. var result = new Array();
  68434. var angle = 0;
  68435. var increment = (Math.PI * 2) / numberOfSides;
  68436. for (var i = 0; i < numberOfSides; i++) {
  68437. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68438. angle -= increment;
  68439. }
  68440. return result;
  68441. };
  68442. Polygon.Parse = function (input) {
  68443. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68444. var i, result = [];
  68445. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68446. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68447. }
  68448. return result;
  68449. };
  68450. Polygon.StartingAt = function (x, y) {
  68451. return BABYLON.Path2.StartingAt(x, y);
  68452. };
  68453. return Polygon;
  68454. }());
  68455. BABYLON.Polygon = Polygon;
  68456. var PolygonMeshBuilder = /** @class */ (function () {
  68457. function PolygonMeshBuilder(name, contours, scene) {
  68458. this._points = new PolygonPoints();
  68459. this._outlinepoints = new PolygonPoints();
  68460. this._holes = new Array();
  68461. this._epoints = new Array();
  68462. this._eholes = new Array();
  68463. this._name = name;
  68464. this._scene = scene;
  68465. var points;
  68466. if (contours instanceof BABYLON.Path2) {
  68467. points = contours.getPoints();
  68468. }
  68469. else {
  68470. points = contours;
  68471. }
  68472. this._addToepoint(points);
  68473. this._points.add(points);
  68474. this._outlinepoints.add(points);
  68475. }
  68476. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  68477. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  68478. var p = points_1[_i];
  68479. this._epoints.push(p.x, p.y);
  68480. }
  68481. };
  68482. PolygonMeshBuilder.prototype.addHole = function (hole) {
  68483. this._points.add(hole);
  68484. var holepoints = new PolygonPoints();
  68485. holepoints.add(hole);
  68486. this._holes.push(holepoints);
  68487. this._eholes.push(this._epoints.length / 2);
  68488. this._addToepoint(hole);
  68489. return this;
  68490. };
  68491. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  68492. var _this = this;
  68493. if (updatable === void 0) { updatable = false; }
  68494. if (depth === void 0) { depth = 0; }
  68495. var result = new BABYLON.Mesh(this._name, this._scene);
  68496. var normals = new Array();
  68497. var positions = new Array();
  68498. var uvs = new Array();
  68499. var bounds = this._points.computeBounds();
  68500. this._points.elements.forEach(function (p) {
  68501. normals.push(0, 1.0, 0);
  68502. positions.push(p.x, 0, p.y);
  68503. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  68504. });
  68505. var indices = new Array();
  68506. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  68507. for (var i = 0; i < res.length; i++) {
  68508. indices.push(res[i]);
  68509. }
  68510. if (depth > 0) {
  68511. var positionscount = (positions.length / 3); //get the current pointcount
  68512. this._points.elements.forEach(function (p) {
  68513. normals.push(0, -1.0, 0);
  68514. positions.push(p.x, -depth, p.y);
  68515. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  68516. });
  68517. var totalCount = indices.length;
  68518. for (var i = 0; i < totalCount; i += 3) {
  68519. var i0 = indices[i + 0];
  68520. var i1 = indices[i + 1];
  68521. var i2 = indices[i + 2];
  68522. indices.push(i2 + positionscount);
  68523. indices.push(i1 + positionscount);
  68524. indices.push(i0 + positionscount);
  68525. }
  68526. //Add the sides
  68527. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  68528. this._holes.forEach(function (hole) {
  68529. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  68530. });
  68531. }
  68532. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  68533. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  68534. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  68535. result.setIndices(indices);
  68536. return result;
  68537. };
  68538. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  68539. var StartIndex = positions.length / 3;
  68540. var ulength = 0;
  68541. for (var i = 0; i < points.elements.length; i++) {
  68542. var p = points.elements[i];
  68543. var p1;
  68544. if ((i + 1) > points.elements.length - 1) {
  68545. p1 = points.elements[0];
  68546. }
  68547. else {
  68548. p1 = points.elements[i + 1];
  68549. }
  68550. positions.push(p.x, 0, p.y);
  68551. positions.push(p.x, -depth, p.y);
  68552. positions.push(p1.x, 0, p1.y);
  68553. positions.push(p1.x, -depth, p1.y);
  68554. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  68555. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  68556. var v3 = v2.subtract(v1);
  68557. var v4 = new BABYLON.Vector3(0, 1, 0);
  68558. var vn = BABYLON.Vector3.Cross(v3, v4);
  68559. vn = vn.normalize();
  68560. uvs.push(ulength / bounds.width, 0);
  68561. uvs.push(ulength / bounds.width, 1);
  68562. ulength += v3.length();
  68563. uvs.push((ulength / bounds.width), 0);
  68564. uvs.push((ulength / bounds.width), 1);
  68565. if (!flip) {
  68566. normals.push(-vn.x, -vn.y, -vn.z);
  68567. normals.push(-vn.x, -vn.y, -vn.z);
  68568. normals.push(-vn.x, -vn.y, -vn.z);
  68569. normals.push(-vn.x, -vn.y, -vn.z);
  68570. indices.push(StartIndex);
  68571. indices.push(StartIndex + 1);
  68572. indices.push(StartIndex + 2);
  68573. indices.push(StartIndex + 1);
  68574. indices.push(StartIndex + 3);
  68575. indices.push(StartIndex + 2);
  68576. }
  68577. else {
  68578. normals.push(vn.x, vn.y, vn.z);
  68579. normals.push(vn.x, vn.y, vn.z);
  68580. normals.push(vn.x, vn.y, vn.z);
  68581. normals.push(vn.x, vn.y, vn.z);
  68582. indices.push(StartIndex);
  68583. indices.push(StartIndex + 2);
  68584. indices.push(StartIndex + 1);
  68585. indices.push(StartIndex + 1);
  68586. indices.push(StartIndex + 2);
  68587. indices.push(StartIndex + 3);
  68588. }
  68589. StartIndex += 4;
  68590. }
  68591. ;
  68592. };
  68593. return PolygonMeshBuilder;
  68594. }());
  68595. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  68596. })(BABYLON || (BABYLON = {}));
  68597. //# sourceMappingURL=babylon.polygonMesh.js.map
  68598. var BABYLON;
  68599. (function (BABYLON) {
  68600. // Unique ID when we import meshes from Babylon to CSG
  68601. var currentCSGMeshId = 0;
  68602. // # class Vertex
  68603. // Represents a vertex of a polygon. Use your own vertex class instead of this
  68604. // one to provide additional features like texture coordinates and vertex
  68605. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  68606. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  68607. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  68608. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  68609. // is not used anywhere else.
  68610. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  68611. var Vertex = /** @class */ (function () {
  68612. function Vertex(pos, normal, uv) {
  68613. this.pos = pos;
  68614. this.normal = normal;
  68615. this.uv = uv;
  68616. }
  68617. Vertex.prototype.clone = function () {
  68618. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  68619. };
  68620. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  68621. // orientation of a polygon is flipped.
  68622. Vertex.prototype.flip = function () {
  68623. this.normal = this.normal.scale(-1);
  68624. };
  68625. // Create a new vertex between this vertex and `other` by linearly
  68626. // interpolating all properties using a parameter of `t`. Subclasses should
  68627. // override this to interpolate additional properties.
  68628. Vertex.prototype.interpolate = function (other, t) {
  68629. 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));
  68630. };
  68631. return Vertex;
  68632. }());
  68633. // # class Plane
  68634. // Represents a plane in 3D space.
  68635. var Plane = /** @class */ (function () {
  68636. function Plane(normal, w) {
  68637. this.normal = normal;
  68638. this.w = w;
  68639. }
  68640. Plane.FromPoints = function (a, b, c) {
  68641. var v0 = c.subtract(a);
  68642. var v1 = b.subtract(a);
  68643. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  68644. return null;
  68645. }
  68646. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  68647. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  68648. };
  68649. Plane.prototype.clone = function () {
  68650. return new Plane(this.normal.clone(), this.w);
  68651. };
  68652. Plane.prototype.flip = function () {
  68653. this.normal.scaleInPlace(-1);
  68654. this.w = -this.w;
  68655. };
  68656. // Split `polygon` by this plane if needed, then put the polygon or polygon
  68657. // fragments in the appropriate lists. Coplanar polygons go into either
  68658. // `coplanarFront` or `coplanarBack` depending on their orientation with
  68659. // respect to this plane. Polygons in front or in back of this plane go into
  68660. // either `front` or `back`.
  68661. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  68662. var COPLANAR = 0;
  68663. var FRONT = 1;
  68664. var BACK = 2;
  68665. var SPANNING = 3;
  68666. // Classify each point as well as the entire polygon into one of the above
  68667. // four classes.
  68668. var polygonType = 0;
  68669. var types = [];
  68670. var i;
  68671. var t;
  68672. for (i = 0; i < polygon.vertices.length; i++) {
  68673. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  68674. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  68675. polygonType |= type;
  68676. types.push(type);
  68677. }
  68678. // Put the polygon in the correct list, splitting it when necessary.
  68679. switch (polygonType) {
  68680. case COPLANAR:
  68681. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  68682. break;
  68683. case FRONT:
  68684. front.push(polygon);
  68685. break;
  68686. case BACK:
  68687. back.push(polygon);
  68688. break;
  68689. case SPANNING:
  68690. var f = [], b = [];
  68691. for (i = 0; i < polygon.vertices.length; i++) {
  68692. var j = (i + 1) % polygon.vertices.length;
  68693. var ti = types[i], tj = types[j];
  68694. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  68695. if (ti !== BACK)
  68696. f.push(vi);
  68697. if (ti !== FRONT)
  68698. b.push(ti !== BACK ? vi.clone() : vi);
  68699. if ((ti | tj) === SPANNING) {
  68700. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  68701. var v = vi.interpolate(vj, t);
  68702. f.push(v);
  68703. b.push(v.clone());
  68704. }
  68705. }
  68706. var poly;
  68707. if (f.length >= 3) {
  68708. poly = new Polygon(f, polygon.shared);
  68709. if (poly.plane)
  68710. front.push(poly);
  68711. }
  68712. if (b.length >= 3) {
  68713. poly = new Polygon(b, polygon.shared);
  68714. if (poly.plane)
  68715. back.push(poly);
  68716. }
  68717. break;
  68718. }
  68719. };
  68720. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  68721. // point is on the plane.
  68722. Plane.EPSILON = 1e-5;
  68723. return Plane;
  68724. }());
  68725. // # class Polygon
  68726. // Represents a convex polygon. The vertices used to initialize a polygon must
  68727. // be coplanar and form a convex loop.
  68728. //
  68729. // Each convex polygon has a `shared` property, which is shared between all
  68730. // polygons that are clones of each other or were split from the same polygon.
  68731. // This can be used to define per-polygon properties (such as surface color).
  68732. var Polygon = /** @class */ (function () {
  68733. function Polygon(vertices, shared) {
  68734. this.vertices = vertices;
  68735. this.shared = shared;
  68736. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  68737. }
  68738. Polygon.prototype.clone = function () {
  68739. var vertices = this.vertices.map(function (v) { return v.clone(); });
  68740. return new Polygon(vertices, this.shared);
  68741. };
  68742. Polygon.prototype.flip = function () {
  68743. this.vertices.reverse().map(function (v) { v.flip(); });
  68744. this.plane.flip();
  68745. };
  68746. return Polygon;
  68747. }());
  68748. // # class Node
  68749. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  68750. // by picking a polygon to split along. That polygon (and all other coplanar
  68751. // polygons) are added directly to that node and the other polygons are added to
  68752. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  68753. // no distinction between internal and leaf nodes.
  68754. var Node = /** @class */ (function () {
  68755. function Node(polygons) {
  68756. this.plane = null;
  68757. this.front = null;
  68758. this.back = null;
  68759. this.polygons = new Array();
  68760. if (polygons) {
  68761. this.build(polygons);
  68762. }
  68763. }
  68764. Node.prototype.clone = function () {
  68765. var node = new Node();
  68766. node.plane = this.plane && this.plane.clone();
  68767. node.front = this.front && this.front.clone();
  68768. node.back = this.back && this.back.clone();
  68769. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  68770. return node;
  68771. };
  68772. // Convert solid space to empty space and empty space to solid space.
  68773. Node.prototype.invert = function () {
  68774. for (var i = 0; i < this.polygons.length; i++) {
  68775. this.polygons[i].flip();
  68776. }
  68777. if (this.plane) {
  68778. this.plane.flip();
  68779. }
  68780. if (this.front) {
  68781. this.front.invert();
  68782. }
  68783. if (this.back) {
  68784. this.back.invert();
  68785. }
  68786. var temp = this.front;
  68787. this.front = this.back;
  68788. this.back = temp;
  68789. };
  68790. // Recursively remove all polygons in `polygons` that are inside this BSP
  68791. // tree.
  68792. Node.prototype.clipPolygons = function (polygons) {
  68793. if (!this.plane)
  68794. return polygons.slice();
  68795. var front = new Array(), back = new Array();
  68796. for (var i = 0; i < polygons.length; i++) {
  68797. this.plane.splitPolygon(polygons[i], front, back, front, back);
  68798. }
  68799. if (this.front) {
  68800. front = this.front.clipPolygons(front);
  68801. }
  68802. if (this.back) {
  68803. back = this.back.clipPolygons(back);
  68804. }
  68805. else {
  68806. back = [];
  68807. }
  68808. return front.concat(back);
  68809. };
  68810. // Remove all polygons in this BSP tree that are inside the other BSP tree
  68811. // `bsp`.
  68812. Node.prototype.clipTo = function (bsp) {
  68813. this.polygons = bsp.clipPolygons(this.polygons);
  68814. if (this.front)
  68815. this.front.clipTo(bsp);
  68816. if (this.back)
  68817. this.back.clipTo(bsp);
  68818. };
  68819. // Return a list of all polygons in this BSP tree.
  68820. Node.prototype.allPolygons = function () {
  68821. var polygons = this.polygons.slice();
  68822. if (this.front)
  68823. polygons = polygons.concat(this.front.allPolygons());
  68824. if (this.back)
  68825. polygons = polygons.concat(this.back.allPolygons());
  68826. return polygons;
  68827. };
  68828. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  68829. // new polygons are filtered down to the bottom of the tree and become new
  68830. // nodes there. Each set of polygons is partitioned using the first polygon
  68831. // (no heuristic is used to pick a good split).
  68832. Node.prototype.build = function (polygons) {
  68833. if (!polygons.length)
  68834. return;
  68835. if (!this.plane)
  68836. this.plane = polygons[0].plane.clone();
  68837. var front = new Array(), back = new Array();
  68838. for (var i = 0; i < polygons.length; i++) {
  68839. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  68840. }
  68841. if (front.length) {
  68842. if (!this.front)
  68843. this.front = new Node();
  68844. this.front.build(front);
  68845. }
  68846. if (back.length) {
  68847. if (!this.back)
  68848. this.back = new Node();
  68849. this.back.build(back);
  68850. }
  68851. };
  68852. return Node;
  68853. }());
  68854. var CSG = /** @class */ (function () {
  68855. function CSG() {
  68856. this.polygons = new Array();
  68857. }
  68858. // Convert BABYLON.Mesh to BABYLON.CSG
  68859. CSG.FromMesh = function (mesh) {
  68860. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  68861. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  68862. if (mesh instanceof BABYLON.Mesh) {
  68863. mesh.computeWorldMatrix(true);
  68864. matrix = mesh.getWorldMatrix();
  68865. meshPosition = mesh.position.clone();
  68866. meshRotation = mesh.rotation.clone();
  68867. if (mesh.rotationQuaternion) {
  68868. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  68869. }
  68870. meshScaling = mesh.scaling.clone();
  68871. }
  68872. else {
  68873. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  68874. }
  68875. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68876. var subMeshes = mesh.subMeshes;
  68877. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  68878. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  68879. vertices = [];
  68880. for (var j = 0; j < 3; j++) {
  68881. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  68882. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  68883. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  68884. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  68885. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  68886. vertex = new Vertex(position, normal, uv);
  68887. vertices.push(vertex);
  68888. }
  68889. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  68890. // To handle the case of degenerated triangle
  68891. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  68892. if (polygon.plane)
  68893. polygons.push(polygon);
  68894. }
  68895. }
  68896. var csg = CSG.FromPolygons(polygons);
  68897. csg.matrix = matrix;
  68898. csg.position = meshPosition;
  68899. csg.rotation = meshRotation;
  68900. csg.scaling = meshScaling;
  68901. csg.rotationQuaternion = meshRotationQuaternion;
  68902. currentCSGMeshId++;
  68903. return csg;
  68904. };
  68905. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  68906. CSG.FromPolygons = function (polygons) {
  68907. var csg = new CSG();
  68908. csg.polygons = polygons;
  68909. return csg;
  68910. };
  68911. CSG.prototype.clone = function () {
  68912. var csg = new CSG();
  68913. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  68914. csg.copyTransformAttributes(this);
  68915. return csg;
  68916. };
  68917. CSG.prototype.union = function (csg) {
  68918. var a = new Node(this.clone().polygons);
  68919. var b = new Node(csg.clone().polygons);
  68920. a.clipTo(b);
  68921. b.clipTo(a);
  68922. b.invert();
  68923. b.clipTo(a);
  68924. b.invert();
  68925. a.build(b.allPolygons());
  68926. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68927. };
  68928. CSG.prototype.unionInPlace = function (csg) {
  68929. var a = new Node(this.polygons);
  68930. var b = new Node(csg.polygons);
  68931. a.clipTo(b);
  68932. b.clipTo(a);
  68933. b.invert();
  68934. b.clipTo(a);
  68935. b.invert();
  68936. a.build(b.allPolygons());
  68937. this.polygons = a.allPolygons();
  68938. };
  68939. CSG.prototype.subtract = function (csg) {
  68940. var a = new Node(this.clone().polygons);
  68941. var b = new Node(csg.clone().polygons);
  68942. a.invert();
  68943. a.clipTo(b);
  68944. b.clipTo(a);
  68945. b.invert();
  68946. b.clipTo(a);
  68947. b.invert();
  68948. a.build(b.allPolygons());
  68949. a.invert();
  68950. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68951. };
  68952. CSG.prototype.subtractInPlace = function (csg) {
  68953. var a = new Node(this.polygons);
  68954. var b = new Node(csg.polygons);
  68955. a.invert();
  68956. a.clipTo(b);
  68957. b.clipTo(a);
  68958. b.invert();
  68959. b.clipTo(a);
  68960. b.invert();
  68961. a.build(b.allPolygons());
  68962. a.invert();
  68963. this.polygons = a.allPolygons();
  68964. };
  68965. CSG.prototype.intersect = function (csg) {
  68966. var a = new Node(this.clone().polygons);
  68967. var b = new Node(csg.clone().polygons);
  68968. a.invert();
  68969. b.clipTo(a);
  68970. b.invert();
  68971. a.clipTo(b);
  68972. b.clipTo(a);
  68973. a.build(b.allPolygons());
  68974. a.invert();
  68975. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68976. };
  68977. CSG.prototype.intersectInPlace = function (csg) {
  68978. var a = new Node(this.polygons);
  68979. var b = new Node(csg.polygons);
  68980. a.invert();
  68981. b.clipTo(a);
  68982. b.invert();
  68983. a.clipTo(b);
  68984. b.clipTo(a);
  68985. a.build(b.allPolygons());
  68986. a.invert();
  68987. this.polygons = a.allPolygons();
  68988. };
  68989. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  68990. // not modified.
  68991. CSG.prototype.inverse = function () {
  68992. var csg = this.clone();
  68993. csg.inverseInPlace();
  68994. return csg;
  68995. };
  68996. CSG.prototype.inverseInPlace = function () {
  68997. this.polygons.map(function (p) { p.flip(); });
  68998. };
  68999. // This is used to keep meshes transformations so they can be restored
  69000. // when we build back a Babylon Mesh
  69001. // NB : All CSG operations are performed in world coordinates
  69002. CSG.prototype.copyTransformAttributes = function (csg) {
  69003. this.matrix = csg.matrix;
  69004. this.position = csg.position;
  69005. this.rotation = csg.rotation;
  69006. this.scaling = csg.scaling;
  69007. this.rotationQuaternion = csg.rotationQuaternion;
  69008. return this;
  69009. };
  69010. // Build Raw mesh from CSG
  69011. // Coordinates here are in world space
  69012. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69013. var matrix = this.matrix.clone();
  69014. matrix.invert();
  69015. 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;
  69016. if (keepSubMeshes) {
  69017. // Sort Polygons, since subMeshes are indices range
  69018. polygons.sort(function (a, b) {
  69019. if (a.shared.meshId === b.shared.meshId) {
  69020. return a.shared.subMeshId - b.shared.subMeshId;
  69021. }
  69022. else {
  69023. return a.shared.meshId - b.shared.meshId;
  69024. }
  69025. });
  69026. }
  69027. for (var i = 0, il = polygons.length; i < il; i++) {
  69028. polygon = polygons[i];
  69029. // Building SubMeshes
  69030. if (!subMesh_dict[polygon.shared.meshId]) {
  69031. subMesh_dict[polygon.shared.meshId] = {};
  69032. }
  69033. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69034. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69035. indexStart: +Infinity,
  69036. indexEnd: -Infinity,
  69037. materialIndex: polygon.shared.materialIndex
  69038. };
  69039. }
  69040. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69041. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69042. polygonIndices[0] = 0;
  69043. polygonIndices[1] = j - 1;
  69044. polygonIndices[2] = j;
  69045. for (var k = 0; k < 3; k++) {
  69046. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69047. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69048. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69049. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69050. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69051. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69052. // Check if 2 points can be merged
  69053. if (!(typeof vertex_idx !== 'undefined' &&
  69054. normals[vertex_idx * 3] === localNormal.x &&
  69055. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69056. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69057. uvs[vertex_idx * 2] === uv.x &&
  69058. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69059. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69060. uvs.push(uv.x, uv.y);
  69061. normals.push(normal.x, normal.y, normal.z);
  69062. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69063. }
  69064. indices.push(vertex_idx);
  69065. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69066. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69067. currentIndex++;
  69068. }
  69069. }
  69070. }
  69071. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69072. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69073. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69074. mesh.setIndices(indices, null);
  69075. if (keepSubMeshes) {
  69076. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69077. var materialIndexOffset = 0, materialMaxIndex;
  69078. mesh.subMeshes = new Array();
  69079. for (var m in subMesh_dict) {
  69080. materialMaxIndex = -1;
  69081. for (var sm in subMesh_dict[m]) {
  69082. subMesh_obj = subMesh_dict[m][sm];
  69083. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69084. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69085. }
  69086. materialIndexOffset += ++materialMaxIndex;
  69087. }
  69088. }
  69089. return mesh;
  69090. };
  69091. // Build Mesh from CSG taking material and transforms into account
  69092. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69093. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69094. mesh.material = material;
  69095. mesh.position.copyFrom(this.position);
  69096. mesh.rotation.copyFrom(this.rotation);
  69097. if (this.rotationQuaternion) {
  69098. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69099. }
  69100. mesh.scaling.copyFrom(this.scaling);
  69101. mesh.computeWorldMatrix(true);
  69102. return mesh;
  69103. };
  69104. return CSG;
  69105. }());
  69106. BABYLON.CSG = CSG;
  69107. })(BABYLON || (BABYLON = {}));
  69108. //# sourceMappingURL=babylon.csg.js.map
  69109. var BABYLON;
  69110. (function (BABYLON) {
  69111. var LensFlare = /** @class */ (function () {
  69112. function LensFlare(size, position, color, imgUrl, system) {
  69113. this.size = size;
  69114. this.position = position;
  69115. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69116. this.color = color || new BABYLON.Color3(1, 1, 1);
  69117. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69118. this._system = system;
  69119. system.lensFlares.push(this);
  69120. }
  69121. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69122. return new LensFlare(size, position, color, imgUrl, system);
  69123. };
  69124. LensFlare.prototype.dispose = function () {
  69125. if (this.texture) {
  69126. this.texture.dispose();
  69127. }
  69128. // Remove from scene
  69129. var index = this._system.lensFlares.indexOf(this);
  69130. this._system.lensFlares.splice(index, 1);
  69131. };
  69132. ;
  69133. return LensFlare;
  69134. }());
  69135. BABYLON.LensFlare = LensFlare;
  69136. })(BABYLON || (BABYLON = {}));
  69137. //# sourceMappingURL=babylon.lensFlare.js.map
  69138. var BABYLON;
  69139. (function (BABYLON) {
  69140. var LensFlareSystem = /** @class */ (function () {
  69141. function LensFlareSystem(name, emitter, scene) {
  69142. this.name = name;
  69143. this.lensFlares = new Array();
  69144. this.borderLimit = 300;
  69145. this.viewportBorder = 0;
  69146. this.layerMask = 0x0FFFFFFF;
  69147. this._vertexBuffers = {};
  69148. this._isEnabled = true;
  69149. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69150. this._emitter = emitter;
  69151. this.id = name;
  69152. scene.lensFlareSystems.push(this);
  69153. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69154. var engine = scene.getEngine();
  69155. // VBO
  69156. var vertices = [];
  69157. vertices.push(1, 1);
  69158. vertices.push(-1, 1);
  69159. vertices.push(-1, -1);
  69160. vertices.push(1, -1);
  69161. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69162. // Indices
  69163. var indices = [];
  69164. indices.push(0);
  69165. indices.push(1);
  69166. indices.push(2);
  69167. indices.push(0);
  69168. indices.push(2);
  69169. indices.push(3);
  69170. this._indexBuffer = engine.createIndexBuffer(indices);
  69171. // Effects
  69172. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69173. }
  69174. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69175. get: function () {
  69176. return this._isEnabled;
  69177. },
  69178. set: function (value) {
  69179. this._isEnabled = value;
  69180. },
  69181. enumerable: true,
  69182. configurable: true
  69183. });
  69184. LensFlareSystem.prototype.getScene = function () {
  69185. return this._scene;
  69186. };
  69187. LensFlareSystem.prototype.getEmitter = function () {
  69188. return this._emitter;
  69189. };
  69190. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69191. this._emitter = newEmitter;
  69192. };
  69193. LensFlareSystem.prototype.getEmitterPosition = function () {
  69194. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69195. };
  69196. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69197. var position = this.getEmitterPosition();
  69198. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69199. this._positionX = position.x;
  69200. this._positionY = position.y;
  69201. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69202. if (this.viewportBorder > 0) {
  69203. globalViewport.x -= this.viewportBorder;
  69204. globalViewport.y -= this.viewportBorder;
  69205. globalViewport.width += this.viewportBorder * 2;
  69206. globalViewport.height += this.viewportBorder * 2;
  69207. position.x += this.viewportBorder;
  69208. position.y += this.viewportBorder;
  69209. this._positionX += this.viewportBorder;
  69210. this._positionY += this.viewportBorder;
  69211. }
  69212. if (position.z > 0) {
  69213. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69214. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69215. return true;
  69216. }
  69217. return true;
  69218. }
  69219. return false;
  69220. };
  69221. LensFlareSystem.prototype._isVisible = function () {
  69222. if (!this._isEnabled || !this._scene.activeCamera) {
  69223. return false;
  69224. }
  69225. var emitterPosition = this.getEmitterPosition();
  69226. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69227. var distance = direction.length();
  69228. direction.normalize();
  69229. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69230. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69231. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69232. };
  69233. LensFlareSystem.prototype.render = function () {
  69234. if (!this._effect.isReady() || !this._scene.activeCamera)
  69235. return false;
  69236. var engine = this._scene.getEngine();
  69237. var viewport = this._scene.activeCamera.viewport;
  69238. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69239. // Position
  69240. if (!this.computeEffectivePosition(globalViewport)) {
  69241. return false;
  69242. }
  69243. // Visibility
  69244. if (!this._isVisible()) {
  69245. return false;
  69246. }
  69247. // Intensity
  69248. var awayX;
  69249. var awayY;
  69250. if (this._positionX < this.borderLimit + globalViewport.x) {
  69251. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69252. }
  69253. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69254. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69255. }
  69256. else {
  69257. awayX = 0;
  69258. }
  69259. if (this._positionY < this.borderLimit + globalViewport.y) {
  69260. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69261. }
  69262. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69263. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69264. }
  69265. else {
  69266. awayY = 0;
  69267. }
  69268. var away = (awayX > awayY) ? awayX : awayY;
  69269. away -= this.viewportBorder;
  69270. if (away > this.borderLimit) {
  69271. away = this.borderLimit;
  69272. }
  69273. var intensity = 1.0 - (away / this.borderLimit);
  69274. if (intensity < 0) {
  69275. return false;
  69276. }
  69277. if (intensity > 1.0) {
  69278. intensity = 1.0;
  69279. }
  69280. if (this.viewportBorder > 0) {
  69281. globalViewport.x += this.viewportBorder;
  69282. globalViewport.y += this.viewportBorder;
  69283. globalViewport.width -= this.viewportBorder * 2;
  69284. globalViewport.height -= this.viewportBorder * 2;
  69285. this._positionX -= this.viewportBorder;
  69286. this._positionY -= this.viewportBorder;
  69287. }
  69288. // Position
  69289. var centerX = globalViewport.x + globalViewport.width / 2;
  69290. var centerY = globalViewport.y + globalViewport.height / 2;
  69291. var distX = centerX - this._positionX;
  69292. var distY = centerY - this._positionY;
  69293. // Effects
  69294. engine.enableEffect(this._effect);
  69295. engine.setState(false);
  69296. engine.setDepthBuffer(false);
  69297. // VBOs
  69298. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69299. // Flares
  69300. for (var index = 0; index < this.lensFlares.length; index++) {
  69301. var flare = this.lensFlares[index];
  69302. engine.setAlphaMode(flare.alphaMode);
  69303. var x = centerX - (distX * flare.position);
  69304. var y = centerY - (distY * flare.position);
  69305. var cw = flare.size;
  69306. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69307. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69308. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69309. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69310. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69311. // Texture
  69312. this._effect.setTexture("textureSampler", flare.texture);
  69313. // Color
  69314. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69315. // Draw order
  69316. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69317. }
  69318. engine.setDepthBuffer(true);
  69319. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69320. return true;
  69321. };
  69322. LensFlareSystem.prototype.dispose = function () {
  69323. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69324. if (vertexBuffer) {
  69325. vertexBuffer.dispose();
  69326. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69327. }
  69328. if (this._indexBuffer) {
  69329. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69330. this._indexBuffer = null;
  69331. }
  69332. while (this.lensFlares.length) {
  69333. this.lensFlares[0].dispose();
  69334. }
  69335. // Remove from scene
  69336. var index = this._scene.lensFlareSystems.indexOf(this);
  69337. this._scene.lensFlareSystems.splice(index, 1);
  69338. };
  69339. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69340. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69341. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69342. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69343. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69344. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69345. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69346. var parsedFlare = parsedLensFlareSystem.flares[index];
  69347. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69348. }
  69349. return lensFlareSystem;
  69350. };
  69351. LensFlareSystem.prototype.serialize = function () {
  69352. var serializationObject = {};
  69353. serializationObject.id = this.id;
  69354. serializationObject.name = this.name;
  69355. serializationObject.emitterId = this.getEmitter().id;
  69356. serializationObject.borderLimit = this.borderLimit;
  69357. serializationObject.flares = [];
  69358. for (var index = 0; index < this.lensFlares.length; index++) {
  69359. var flare = this.lensFlares[index];
  69360. serializationObject.flares.push({
  69361. size: flare.size,
  69362. position: flare.position,
  69363. color: flare.color.asArray(),
  69364. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69365. });
  69366. }
  69367. return serializationObject;
  69368. };
  69369. return LensFlareSystem;
  69370. }());
  69371. BABYLON.LensFlareSystem = LensFlareSystem;
  69372. })(BABYLON || (BABYLON = {}));
  69373. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69374. var BABYLON;
  69375. (function (BABYLON) {
  69376. /**
  69377. * This is a holder class for the physics joint created by the physics plugin.
  69378. * It holds a set of functions to control the underlying joint.
  69379. */
  69380. var PhysicsJoint = /** @class */ (function () {
  69381. function PhysicsJoint(type, jointData) {
  69382. this.type = type;
  69383. this.jointData = jointData;
  69384. jointData.nativeParams = jointData.nativeParams || {};
  69385. }
  69386. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69387. get: function () {
  69388. return this._physicsJoint;
  69389. },
  69390. set: function (newJoint) {
  69391. if (this._physicsJoint) {
  69392. //remove from the wolrd
  69393. }
  69394. this._physicsJoint = newJoint;
  69395. },
  69396. enumerable: true,
  69397. configurable: true
  69398. });
  69399. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69400. set: function (physicsPlugin) {
  69401. this._physicsPlugin = physicsPlugin;
  69402. },
  69403. enumerable: true,
  69404. configurable: true
  69405. });
  69406. /**
  69407. * Execute a function that is physics-plugin specific.
  69408. * @param {Function} func the function that will be executed.
  69409. * It accepts two parameters: the physics world and the physics joint.
  69410. */
  69411. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69412. func(this._physicsPlugin.world, this._physicsJoint);
  69413. };
  69414. //TODO check if the native joints are the same
  69415. //Joint Types
  69416. PhysicsJoint.DistanceJoint = 0;
  69417. PhysicsJoint.HingeJoint = 1;
  69418. PhysicsJoint.BallAndSocketJoint = 2;
  69419. PhysicsJoint.WheelJoint = 3;
  69420. PhysicsJoint.SliderJoint = 4;
  69421. //OIMO
  69422. PhysicsJoint.PrismaticJoint = 5;
  69423. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69424. PhysicsJoint.UniversalJoint = 6;
  69425. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69426. //Cannon
  69427. //Similar to a Ball-Joint. Different in params
  69428. PhysicsJoint.PointToPointJoint = 8;
  69429. //Cannon only at the moment
  69430. PhysicsJoint.SpringJoint = 9;
  69431. PhysicsJoint.LockJoint = 10;
  69432. return PhysicsJoint;
  69433. }());
  69434. BABYLON.PhysicsJoint = PhysicsJoint;
  69435. /**
  69436. * A class representing a physics distance joint.
  69437. */
  69438. var DistanceJoint = /** @class */ (function (_super) {
  69439. __extends(DistanceJoint, _super);
  69440. function DistanceJoint(jointData) {
  69441. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69442. }
  69443. /**
  69444. * Update the predefined distance.
  69445. */
  69446. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69447. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69448. };
  69449. return DistanceJoint;
  69450. }(PhysicsJoint));
  69451. BABYLON.DistanceJoint = DistanceJoint;
  69452. var MotorEnabledJoint = /** @class */ (function (_super) {
  69453. __extends(MotorEnabledJoint, _super);
  69454. function MotorEnabledJoint(type, jointData) {
  69455. return _super.call(this, type, jointData) || this;
  69456. }
  69457. /**
  69458. * Set the motor values.
  69459. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69460. * @param {number} force the force to apply
  69461. * @param {number} maxForce max force for this motor.
  69462. */
  69463. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69464. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69465. };
  69466. /**
  69467. * Set the motor's limits.
  69468. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69469. */
  69470. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69471. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69472. };
  69473. return MotorEnabledJoint;
  69474. }(PhysicsJoint));
  69475. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  69476. /**
  69477. * This class represents a single hinge physics joint
  69478. */
  69479. var HingeJoint = /** @class */ (function (_super) {
  69480. __extends(HingeJoint, _super);
  69481. function HingeJoint(jointData) {
  69482. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  69483. }
  69484. /**
  69485. * Set the motor values.
  69486. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69487. * @param {number} force the force to apply
  69488. * @param {number} maxForce max force for this motor.
  69489. */
  69490. HingeJoint.prototype.setMotor = function (force, maxForce) {
  69491. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69492. };
  69493. /**
  69494. * Set the motor's limits.
  69495. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69496. */
  69497. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69498. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69499. };
  69500. return HingeJoint;
  69501. }(MotorEnabledJoint));
  69502. BABYLON.HingeJoint = HingeJoint;
  69503. /**
  69504. * This class represents a dual hinge physics joint (same as wheel joint)
  69505. */
  69506. var Hinge2Joint = /** @class */ (function (_super) {
  69507. __extends(Hinge2Joint, _super);
  69508. function Hinge2Joint(jointData) {
  69509. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  69510. }
  69511. /**
  69512. * Set the motor values.
  69513. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69514. * @param {number} force the force to apply
  69515. * @param {number} maxForce max force for this motor.
  69516. * @param {motorIndex} the motor's index, 0 or 1.
  69517. */
  69518. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  69519. if (motorIndex === void 0) { motorIndex = 0; }
  69520. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  69521. };
  69522. /**
  69523. * Set the motor limits.
  69524. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69525. * @param {number} upperLimit the upper limit
  69526. * @param {number} lowerLimit lower limit
  69527. * @param {motorIndex} the motor's index, 0 or 1.
  69528. */
  69529. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  69530. if (motorIndex === void 0) { motorIndex = 0; }
  69531. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  69532. };
  69533. return Hinge2Joint;
  69534. }(MotorEnabledJoint));
  69535. BABYLON.Hinge2Joint = Hinge2Joint;
  69536. })(BABYLON || (BABYLON = {}));
  69537. //# sourceMappingURL=babylon.physicsJoint.js.map
  69538. var BABYLON;
  69539. (function (BABYLON) {
  69540. var PhysicsImpostor = /** @class */ (function () {
  69541. function PhysicsImpostor(object, type, _options, _scene) {
  69542. if (_options === void 0) { _options = { mass: 0 }; }
  69543. var _this = this;
  69544. this.object = object;
  69545. this.type = type;
  69546. this._options = _options;
  69547. this._scene = _scene;
  69548. this._bodyUpdateRequired = false;
  69549. this._onBeforePhysicsStepCallbacks = new Array();
  69550. this._onAfterPhysicsStepCallbacks = new Array();
  69551. this._onPhysicsCollideCallbacks = [];
  69552. this._deltaPosition = BABYLON.Vector3.Zero();
  69553. this._isDisposed = false;
  69554. //temp variables for parent rotation calculations
  69555. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  69556. this._tmpQuat = new BABYLON.Quaternion();
  69557. this._tmpQuat2 = new BABYLON.Quaternion();
  69558. /**
  69559. * this function is executed by the physics engine.
  69560. */
  69561. this.beforeStep = function () {
  69562. if (!_this._physicsEngine) {
  69563. return;
  69564. }
  69565. _this.object.translate(_this._deltaPosition, -1);
  69566. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  69567. _this.object.computeWorldMatrix(false);
  69568. if (_this.object.parent && _this.object.rotationQuaternion) {
  69569. _this.getParentsRotation();
  69570. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  69571. }
  69572. else {
  69573. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  69574. }
  69575. if (!_this._options.disableBidirectionalTransformation) {
  69576. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  69577. }
  69578. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  69579. func(_this);
  69580. });
  69581. };
  69582. /**
  69583. * this function is executed by the physics engine.
  69584. */
  69585. this.afterStep = function () {
  69586. if (!_this._physicsEngine) {
  69587. return;
  69588. }
  69589. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  69590. func(_this);
  69591. });
  69592. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  69593. // object has now its world rotation. needs to be converted to local.
  69594. if (_this.object.parent && _this.object.rotationQuaternion) {
  69595. _this.getParentsRotation();
  69596. _this._tmpQuat.conjugateInPlace();
  69597. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  69598. }
  69599. // take the position set and make it the absolute position of this object.
  69600. _this.object.setAbsolutePosition(_this.object.position);
  69601. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  69602. _this.object.translate(_this._deltaPosition, 1);
  69603. };
  69604. /**
  69605. * Legacy collision detection event support
  69606. */
  69607. this.onCollideEvent = null;
  69608. //event and body object due to cannon's event-based architecture.
  69609. this.onCollide = function (e) {
  69610. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  69611. return;
  69612. }
  69613. if (!_this._physicsEngine) {
  69614. return;
  69615. }
  69616. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  69617. if (otherImpostor) {
  69618. // Legacy collision detection event support
  69619. if (_this.onCollideEvent) {
  69620. _this.onCollideEvent(_this, otherImpostor);
  69621. }
  69622. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  69623. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  69624. }).forEach(function (obj) {
  69625. obj.callback(_this, otherImpostor);
  69626. });
  69627. }
  69628. };
  69629. //sanity check!
  69630. if (!this.object) {
  69631. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  69632. return;
  69633. }
  69634. //legacy support for old syntax.
  69635. if (!this._scene && object.getScene) {
  69636. this._scene = object.getScene();
  69637. }
  69638. if (!this._scene) {
  69639. return;
  69640. }
  69641. this._physicsEngine = this._scene.getPhysicsEngine();
  69642. if (!this._physicsEngine) {
  69643. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  69644. }
  69645. else {
  69646. //set the object's quaternion, if not set
  69647. if (!this.object.rotationQuaternion) {
  69648. if (this.object.rotation) {
  69649. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  69650. }
  69651. else {
  69652. this.object.rotationQuaternion = new BABYLON.Quaternion();
  69653. }
  69654. }
  69655. //default options params
  69656. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  69657. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  69658. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  69659. this._joints = [];
  69660. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  69661. if (!this.object.parent || this._options.ignoreParent) {
  69662. this._init();
  69663. }
  69664. else if (this.object.parent.physicsImpostor) {
  69665. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  69666. }
  69667. }
  69668. }
  69669. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  69670. get: function () {
  69671. return this._isDisposed;
  69672. },
  69673. enumerable: true,
  69674. configurable: true
  69675. });
  69676. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  69677. get: function () {
  69678. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  69679. },
  69680. set: function (value) {
  69681. this.setMass(value);
  69682. },
  69683. enumerable: true,
  69684. configurable: true
  69685. });
  69686. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  69687. get: function () {
  69688. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  69689. },
  69690. set: function (value) {
  69691. if (!this._physicsEngine) {
  69692. return;
  69693. }
  69694. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  69695. },
  69696. enumerable: true,
  69697. configurable: true
  69698. });
  69699. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  69700. get: function () {
  69701. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  69702. },
  69703. set: function (value) {
  69704. if (!this._physicsEngine) {
  69705. return;
  69706. }
  69707. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  69708. },
  69709. enumerable: true,
  69710. configurable: true
  69711. });
  69712. /**
  69713. * This function will completly initialize this impostor.
  69714. * It will create a new body - but only if this mesh has no parent.
  69715. * If it has, this impostor will not be used other than to define the impostor
  69716. * of the child mesh.
  69717. */
  69718. PhysicsImpostor.prototype._init = function () {
  69719. if (!this._physicsEngine) {
  69720. return;
  69721. }
  69722. this._physicsEngine.removeImpostor(this);
  69723. this.physicsBody = null;
  69724. this._parent = this._parent || this._getPhysicsParent();
  69725. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  69726. this._physicsEngine.addImpostor(this);
  69727. }
  69728. };
  69729. PhysicsImpostor.prototype._getPhysicsParent = function () {
  69730. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  69731. var parentMesh = this.object.parent;
  69732. return parentMesh.physicsImpostor;
  69733. }
  69734. return null;
  69735. };
  69736. /**
  69737. * Should a new body be generated.
  69738. */
  69739. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  69740. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  69741. };
  69742. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  69743. this.forceUpdate();
  69744. };
  69745. /**
  69746. * Force a regeneration of this or the parent's impostor's body.
  69747. * Use under cautious - This will remove all joints already implemented.
  69748. */
  69749. PhysicsImpostor.prototype.forceUpdate = function () {
  69750. this._init();
  69751. if (this.parent && !this._options.ignoreParent) {
  69752. this.parent.forceUpdate();
  69753. }
  69754. };
  69755. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  69756. /*public get mesh(): AbstractMesh {
  69757. return this._mesh;
  69758. }*/
  69759. /**
  69760. * Gets the body that holds this impostor. Either its own, or its parent.
  69761. */
  69762. get: function () {
  69763. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  69764. },
  69765. /**
  69766. * Set the physics body. Used mainly by the physics engine/plugin
  69767. */
  69768. set: function (physicsBody) {
  69769. if (this._physicsBody && this._physicsEngine) {
  69770. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  69771. }
  69772. this._physicsBody = physicsBody;
  69773. this.resetUpdateFlags();
  69774. },
  69775. enumerable: true,
  69776. configurable: true
  69777. });
  69778. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  69779. get: function () {
  69780. return !this._options.ignoreParent && this._parent ? this._parent : null;
  69781. },
  69782. set: function (value) {
  69783. this._parent = value;
  69784. },
  69785. enumerable: true,
  69786. configurable: true
  69787. });
  69788. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  69789. this._bodyUpdateRequired = false;
  69790. };
  69791. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  69792. if (this.object.getBoundingInfo) {
  69793. var q = this.object.rotationQuaternion;
  69794. //reset rotation
  69795. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  69796. //calculate the world matrix with no rotation
  69797. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69798. var boundingInfo = this.object.getBoundingInfo();
  69799. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  69800. //bring back the rotation
  69801. this.object.rotationQuaternion = q;
  69802. //calculate the world matrix with the new rotation
  69803. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69804. return size;
  69805. }
  69806. else {
  69807. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  69808. }
  69809. };
  69810. PhysicsImpostor.prototype.getObjectCenter = function () {
  69811. if (this.object.getBoundingInfo) {
  69812. var boundingInfo = this.object.getBoundingInfo();
  69813. return boundingInfo.boundingBox.centerWorld;
  69814. }
  69815. else {
  69816. return this.object.position;
  69817. }
  69818. };
  69819. /**
  69820. * Get a specific parametes from the options parameter.
  69821. */
  69822. PhysicsImpostor.prototype.getParam = function (paramName) {
  69823. return this._options[paramName];
  69824. };
  69825. /**
  69826. * Sets a specific parameter in the options given to the physics plugin
  69827. */
  69828. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  69829. this._options[paramName] = value;
  69830. this._bodyUpdateRequired = true;
  69831. };
  69832. /**
  69833. * Specifically change the body's mass option. Won't recreate the physics body object
  69834. */
  69835. PhysicsImpostor.prototype.setMass = function (mass) {
  69836. if (this.getParam("mass") !== mass) {
  69837. this.setParam("mass", mass);
  69838. }
  69839. if (this._physicsEngine) {
  69840. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  69841. }
  69842. };
  69843. PhysicsImpostor.prototype.getLinearVelocity = function () {
  69844. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  69845. };
  69846. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  69847. if (this._physicsEngine) {
  69848. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  69849. }
  69850. };
  69851. PhysicsImpostor.prototype.getAngularVelocity = function () {
  69852. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  69853. };
  69854. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  69855. if (this._physicsEngine) {
  69856. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  69857. }
  69858. };
  69859. /**
  69860. * Execute a function with the physics plugin native code.
  69861. * Provide a function the will have two variables - the world object and the physics body object.
  69862. */
  69863. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  69864. if (this._physicsEngine) {
  69865. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  69866. }
  69867. };
  69868. /**
  69869. * Register a function that will be executed before the physics world is stepping forward.
  69870. */
  69871. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  69872. this._onBeforePhysicsStepCallbacks.push(func);
  69873. };
  69874. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  69875. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  69876. if (index > -1) {
  69877. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  69878. }
  69879. else {
  69880. BABYLON.Tools.Warn("Function to remove was not found");
  69881. }
  69882. };
  69883. /**
  69884. * Register a function that will be executed after the physics step
  69885. */
  69886. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  69887. this._onAfterPhysicsStepCallbacks.push(func);
  69888. };
  69889. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  69890. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  69891. if (index > -1) {
  69892. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  69893. }
  69894. else {
  69895. BABYLON.Tools.Warn("Function to remove was not found");
  69896. }
  69897. };
  69898. /**
  69899. * register a function that will be executed when this impostor collides against a different body.
  69900. */
  69901. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  69902. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  69903. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  69904. };
  69905. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  69906. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  69907. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  69908. if (index > -1) {
  69909. this._onPhysicsCollideCallbacks.splice(index, 1);
  69910. }
  69911. else {
  69912. BABYLON.Tools.Warn("Function to remove was not found");
  69913. }
  69914. };
  69915. PhysicsImpostor.prototype.getParentsRotation = function () {
  69916. var parent = this.object.parent;
  69917. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  69918. while (parent) {
  69919. if (parent.rotationQuaternion) {
  69920. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  69921. }
  69922. else {
  69923. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  69924. }
  69925. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  69926. parent = parent.parent;
  69927. }
  69928. return this._tmpQuat;
  69929. };
  69930. /**
  69931. * Apply a force
  69932. */
  69933. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  69934. if (this._physicsEngine) {
  69935. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  69936. }
  69937. return this;
  69938. };
  69939. /**
  69940. * Apply an impulse
  69941. */
  69942. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  69943. if (this._physicsEngine) {
  69944. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  69945. }
  69946. return this;
  69947. };
  69948. /**
  69949. * A help function to create a joint.
  69950. */
  69951. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  69952. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  69953. this.addJoint(otherImpostor, joint);
  69954. return this;
  69955. };
  69956. /**
  69957. * Add a joint to this impostor with a different impostor.
  69958. */
  69959. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  69960. this._joints.push({
  69961. otherImpostor: otherImpostor,
  69962. joint: joint
  69963. });
  69964. if (this._physicsEngine) {
  69965. this._physicsEngine.addJoint(this, otherImpostor, joint);
  69966. }
  69967. return this;
  69968. };
  69969. /**
  69970. * Will keep this body still, in a sleep mode.
  69971. */
  69972. PhysicsImpostor.prototype.sleep = function () {
  69973. if (this._physicsEngine) {
  69974. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  69975. }
  69976. return this;
  69977. };
  69978. /**
  69979. * Wake the body up.
  69980. */
  69981. PhysicsImpostor.prototype.wakeUp = function () {
  69982. if (this._physicsEngine) {
  69983. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  69984. }
  69985. return this;
  69986. };
  69987. PhysicsImpostor.prototype.clone = function (newObject) {
  69988. if (!newObject)
  69989. return null;
  69990. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  69991. };
  69992. PhysicsImpostor.prototype.dispose = function () {
  69993. var _this = this;
  69994. //no dispose if no physics engine is available.
  69995. if (!this._physicsEngine) {
  69996. return;
  69997. }
  69998. this._joints.forEach(function (j) {
  69999. if (_this._physicsEngine) {
  70000. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70001. }
  70002. });
  70003. //dispose the physics body
  70004. this._physicsEngine.removeImpostor(this);
  70005. if (this.parent) {
  70006. this.parent.forceUpdate();
  70007. }
  70008. else {
  70009. /*this._object.getChildMeshes().forEach(function(mesh) {
  70010. if (mesh.physicsImpostor) {
  70011. if (disposeChildren) {
  70012. mesh.physicsImpostor.dispose();
  70013. mesh.physicsImpostor = null;
  70014. }
  70015. }
  70016. })*/
  70017. }
  70018. this._isDisposed = true;
  70019. };
  70020. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70021. this._deltaPosition.copyFrom(position);
  70022. };
  70023. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70024. if (!this._deltaRotation) {
  70025. this._deltaRotation = new BABYLON.Quaternion();
  70026. }
  70027. this._deltaRotation.copyFrom(rotation);
  70028. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70029. };
  70030. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70031. if (this._physicsEngine) {
  70032. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70033. }
  70034. return this;
  70035. };
  70036. PhysicsImpostor.prototype.getRadius = function () {
  70037. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70038. };
  70039. /**
  70040. * Sync a bone with this impostor
  70041. * @param bone The bone to sync to the impostor.
  70042. * @param boneMesh The mesh that the bone is influencing.
  70043. * @param jointPivot The pivot of the joint / bone in local space.
  70044. * @param distToJoint Optional distance from the impostor to the joint.
  70045. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70046. */
  70047. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70048. var tempVec = PhysicsImpostor._tmpVecs[0];
  70049. var mesh = this.object;
  70050. if (mesh.rotationQuaternion) {
  70051. if (adjustRotation) {
  70052. var tempQuat = PhysicsImpostor._tmpQuat;
  70053. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70054. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70055. }
  70056. else {
  70057. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70058. }
  70059. }
  70060. tempVec.x = 0;
  70061. tempVec.y = 0;
  70062. tempVec.z = 0;
  70063. if (jointPivot) {
  70064. tempVec.x = jointPivot.x;
  70065. tempVec.y = jointPivot.y;
  70066. tempVec.z = jointPivot.z;
  70067. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70068. if (distToJoint === undefined || distToJoint === null) {
  70069. distToJoint = jointPivot.length();
  70070. }
  70071. tempVec.x *= distToJoint;
  70072. tempVec.y *= distToJoint;
  70073. tempVec.z *= distToJoint;
  70074. }
  70075. if (bone.getParent()) {
  70076. tempVec.addInPlace(mesh.getAbsolutePosition());
  70077. bone.setAbsolutePosition(tempVec, boneMesh);
  70078. }
  70079. else {
  70080. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70081. boneMesh.position.x -= tempVec.x;
  70082. boneMesh.position.y -= tempVec.y;
  70083. boneMesh.position.z -= tempVec.z;
  70084. }
  70085. };
  70086. /**
  70087. * Sync impostor to a bone
  70088. * @param bone The bone that the impostor will be synced to.
  70089. * @param boneMesh The mesh that the bone is influencing.
  70090. * @param jointPivot The pivot of the joint / bone in local space.
  70091. * @param distToJoint Optional distance from the impostor to the joint.
  70092. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70093. * @param boneAxis Optional vector3 axis the bone is aligned with
  70094. */
  70095. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70096. var mesh = this.object;
  70097. if (mesh.rotationQuaternion) {
  70098. if (adjustRotation) {
  70099. var tempQuat = PhysicsImpostor._tmpQuat;
  70100. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70101. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70102. }
  70103. else {
  70104. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70105. }
  70106. }
  70107. var pos = PhysicsImpostor._tmpVecs[0];
  70108. var boneDir = PhysicsImpostor._tmpVecs[1];
  70109. if (!boneAxis) {
  70110. boneAxis = PhysicsImpostor._tmpVecs[2];
  70111. boneAxis.x = 0;
  70112. boneAxis.y = 1;
  70113. boneAxis.z = 0;
  70114. }
  70115. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70116. bone.getAbsolutePositionToRef(boneMesh, pos);
  70117. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70118. distToJoint = jointPivot.length();
  70119. }
  70120. if (distToJoint !== undefined && distToJoint !== null) {
  70121. pos.x += boneDir.x * distToJoint;
  70122. pos.y += boneDir.y * distToJoint;
  70123. pos.z += boneDir.z * distToJoint;
  70124. }
  70125. mesh.setAbsolutePosition(pos);
  70126. };
  70127. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70128. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70129. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70130. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70131. //Impostor types
  70132. PhysicsImpostor.NoImpostor = 0;
  70133. PhysicsImpostor.SphereImpostor = 1;
  70134. PhysicsImpostor.BoxImpostor = 2;
  70135. PhysicsImpostor.PlaneImpostor = 3;
  70136. PhysicsImpostor.MeshImpostor = 4;
  70137. PhysicsImpostor.CylinderImpostor = 7;
  70138. PhysicsImpostor.ParticleImpostor = 8;
  70139. PhysicsImpostor.HeightmapImpostor = 9;
  70140. return PhysicsImpostor;
  70141. }());
  70142. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70143. })(BABYLON || (BABYLON = {}));
  70144. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70145. var BABYLON;
  70146. (function (BABYLON) {
  70147. var PhysicsEngine = /** @class */ (function () {
  70148. function PhysicsEngine(gravity, _physicsPlugin) {
  70149. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70150. this._physicsPlugin = _physicsPlugin;
  70151. //new methods and parameters
  70152. this._impostors = [];
  70153. this._joints = [];
  70154. if (!this._physicsPlugin.isSupported()) {
  70155. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70156. + "Please make sure it is included.");
  70157. }
  70158. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70159. this.setGravity(gravity);
  70160. this.setTimeStep();
  70161. }
  70162. PhysicsEngine.prototype.setGravity = function (gravity) {
  70163. this.gravity = gravity;
  70164. this._physicsPlugin.setGravity(this.gravity);
  70165. };
  70166. /**
  70167. * Set the time step of the physics engine.
  70168. * default is 1/60.
  70169. * To slow it down, enter 1/600 for example.
  70170. * To speed it up, 1/30
  70171. * @param {number} newTimeStep the new timestep to apply to this world.
  70172. */
  70173. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70174. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70175. this._physicsPlugin.setTimeStep(newTimeStep);
  70176. };
  70177. /**
  70178. * Get the time step of the physics engine.
  70179. */
  70180. PhysicsEngine.prototype.getTimeStep = function () {
  70181. return this._physicsPlugin.getTimeStep();
  70182. };
  70183. PhysicsEngine.prototype.dispose = function () {
  70184. this._impostors.forEach(function (impostor) {
  70185. impostor.dispose();
  70186. });
  70187. this._physicsPlugin.dispose();
  70188. };
  70189. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70190. return this._physicsPlugin.name;
  70191. };
  70192. /**
  70193. * Adding a new impostor for the impostor tracking.
  70194. * This will be done by the impostor itself.
  70195. * @param {PhysicsImpostor} impostor the impostor to add
  70196. */
  70197. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70198. impostor.uniqueId = this._impostors.push(impostor);
  70199. //if no parent, generate the body
  70200. if (!impostor.parent) {
  70201. this._physicsPlugin.generatePhysicsBody(impostor);
  70202. }
  70203. };
  70204. /**
  70205. * Remove an impostor from the engine.
  70206. * This impostor and its mesh will not longer be updated by the physics engine.
  70207. * @param {PhysicsImpostor} impostor the impostor to remove
  70208. */
  70209. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70210. var index = this._impostors.indexOf(impostor);
  70211. if (index > -1) {
  70212. var removed = this._impostors.splice(index, 1);
  70213. //Is it needed?
  70214. if (removed.length) {
  70215. //this will also remove it from the world.
  70216. removed[0].physicsBody = null;
  70217. }
  70218. }
  70219. };
  70220. /**
  70221. * Add a joint to the physics engine
  70222. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70223. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70224. * @param {PhysicsJoint} the joint that will connect both impostors.
  70225. */
  70226. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70227. var impostorJoint = {
  70228. mainImpostor: mainImpostor,
  70229. connectedImpostor: connectedImpostor,
  70230. joint: joint
  70231. };
  70232. joint.physicsPlugin = this._physicsPlugin;
  70233. this._joints.push(impostorJoint);
  70234. this._physicsPlugin.generateJoint(impostorJoint);
  70235. };
  70236. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70237. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70238. return (impostorJoint.connectedImpostor === connectedImpostor
  70239. && impostorJoint.joint === joint
  70240. && impostorJoint.mainImpostor === mainImpostor);
  70241. });
  70242. if (matchingJoints.length) {
  70243. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70244. //TODO remove it from the list as well
  70245. }
  70246. };
  70247. /**
  70248. * Called by the scene. no need to call it.
  70249. */
  70250. PhysicsEngine.prototype._step = function (delta) {
  70251. var _this = this;
  70252. //check if any mesh has no body / requires an update
  70253. this._impostors.forEach(function (impostor) {
  70254. if (impostor.isBodyInitRequired()) {
  70255. _this._physicsPlugin.generatePhysicsBody(impostor);
  70256. }
  70257. });
  70258. if (delta > 0.1) {
  70259. delta = 0.1;
  70260. }
  70261. else if (delta <= 0) {
  70262. delta = 1.0 / 60.0;
  70263. }
  70264. this._physicsPlugin.executeStep(delta, this._impostors);
  70265. };
  70266. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70267. return this._physicsPlugin;
  70268. };
  70269. PhysicsEngine.prototype.getImpostors = function () {
  70270. return this._impostors;
  70271. };
  70272. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70273. for (var i = 0; i < this._impostors.length; ++i) {
  70274. if (this._impostors[i].object === object) {
  70275. return this._impostors[i];
  70276. }
  70277. }
  70278. return null;
  70279. };
  70280. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70281. for (var i = 0; i < this._impostors.length; ++i) {
  70282. if (this._impostors[i].physicsBody === body) {
  70283. return this._impostors[i];
  70284. }
  70285. }
  70286. return null;
  70287. };
  70288. // Statics
  70289. PhysicsEngine.Epsilon = 0.001;
  70290. return PhysicsEngine;
  70291. }());
  70292. BABYLON.PhysicsEngine = PhysicsEngine;
  70293. })(BABYLON || (BABYLON = {}));
  70294. //# sourceMappingURL=babylon.physicsEngine.js.map
  70295. var BABYLON;
  70296. (function (BABYLON) {
  70297. var PhysicsHelper = /** @class */ (function () {
  70298. function PhysicsHelper(scene) {
  70299. this._scene = scene;
  70300. this._physicsEngine = this._scene.getPhysicsEngine();
  70301. if (!this._physicsEngine) {
  70302. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70303. }
  70304. }
  70305. /**
  70306. * @param {Vector3} origin the origin of the explosion
  70307. * @param {number} radius the explosion radius
  70308. * @param {number} strength the explosion strength
  70309. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70310. */
  70311. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70312. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70313. if (!this._physicsEngine) {
  70314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70315. return null;
  70316. }
  70317. var impostors = this._physicsEngine.getImpostors();
  70318. if (impostors.length === 0) {
  70319. return null;
  70320. }
  70321. var event = new PhysicsRadialExplosionEvent(this._scene);
  70322. impostors.forEach(function (impostor) {
  70323. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70324. if (!impostorForceAndContactPoint) {
  70325. return;
  70326. }
  70327. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70328. });
  70329. event.dispose(false);
  70330. return event;
  70331. };
  70332. /**
  70333. * @param {Vector3} origin the origin of the explosion
  70334. * @param {number} radius the explosion radius
  70335. * @param {number} strength the explosion strength
  70336. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70337. */
  70338. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70339. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70340. if (!this._physicsEngine) {
  70341. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70342. return null;
  70343. }
  70344. var impostors = this._physicsEngine.getImpostors();
  70345. if (impostors.length === 0) {
  70346. return null;
  70347. }
  70348. var event = new PhysicsRadialExplosionEvent(this._scene);
  70349. impostors.forEach(function (impostor) {
  70350. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70351. if (!impostorForceAndContactPoint) {
  70352. return;
  70353. }
  70354. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70355. });
  70356. event.dispose(false);
  70357. return event;
  70358. };
  70359. /**
  70360. * @param {Vector3} origin the origin of the explosion
  70361. * @param {number} radius the explosion radius
  70362. * @param {number} strength the explosion strength
  70363. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70364. */
  70365. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70366. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70367. if (!this._physicsEngine) {
  70368. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70369. return null;
  70370. }
  70371. var impostors = this._physicsEngine.getImpostors();
  70372. if (impostors.length === 0) {
  70373. return null;
  70374. }
  70375. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70376. event.dispose(false);
  70377. return event;
  70378. };
  70379. /**
  70380. * @param {Vector3} origin the origin of the updraft
  70381. * @param {number} radius the radius of the updraft
  70382. * @param {number} strength the strength of the updraft
  70383. * @param {number} height the height of the updraft
  70384. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70385. */
  70386. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70387. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70388. if (!this._physicsEngine) {
  70389. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70390. return null;
  70391. }
  70392. if (this._physicsEngine.getImpostors().length === 0) {
  70393. return null;
  70394. }
  70395. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70396. event.dispose(false);
  70397. return event;
  70398. };
  70399. /**
  70400. * @param {Vector3} origin the of the vortex
  70401. * @param {number} radius the radius of the vortex
  70402. * @param {number} strength the strength of the vortex
  70403. * @param {number} height the height of the vortex
  70404. */
  70405. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70406. if (!this._physicsEngine) {
  70407. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70408. return null;
  70409. }
  70410. if (this._physicsEngine.getImpostors().length === 0) {
  70411. return null;
  70412. }
  70413. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70414. event.dispose(false);
  70415. return event;
  70416. };
  70417. return PhysicsHelper;
  70418. }());
  70419. BABYLON.PhysicsHelper = PhysicsHelper;
  70420. /***** Radial explosion *****/
  70421. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70422. function PhysicsRadialExplosionEvent(scene) {
  70423. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70424. this._rays = [];
  70425. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70426. this._scene = scene;
  70427. }
  70428. /**
  70429. * Returns the data related to the radial explosion event (sphere & rays).
  70430. * @returns {PhysicsRadialExplosionEventData}
  70431. */
  70432. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70433. this._dataFetched = true;
  70434. return {
  70435. sphere: this._sphere,
  70436. rays: this._rays,
  70437. };
  70438. };
  70439. /**
  70440. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70441. * @param impostor
  70442. * @param {Vector3} origin the origin of the explosion
  70443. * @param {number} radius the explosion radius
  70444. * @param {number} strength the explosion strength
  70445. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70446. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70447. */
  70448. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70449. if (impostor.mass === 0) {
  70450. return null;
  70451. }
  70452. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70453. return null;
  70454. }
  70455. if (impostor.object.getClassName() !== 'Mesh') {
  70456. return null;
  70457. }
  70458. var impostorObject = impostor.object;
  70459. var impostorObjectCenter = impostor.getObjectCenter();
  70460. var direction = impostorObjectCenter.subtract(origin);
  70461. var ray = new BABYLON.Ray(origin, direction, radius);
  70462. this._rays.push(ray);
  70463. var hit = ray.intersectsMesh(impostorObject);
  70464. var contactPoint = hit.pickedPoint;
  70465. if (!contactPoint) {
  70466. return null;
  70467. }
  70468. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  70469. if (distanceFromOrigin > radius) {
  70470. return null;
  70471. }
  70472. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  70473. ? strength
  70474. : strength * (1 - (distanceFromOrigin / radius));
  70475. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70476. return { force: force, contactPoint: contactPoint };
  70477. };
  70478. /**
  70479. * Disposes the sphere.
  70480. * @param {bolean} force
  70481. */
  70482. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  70483. var _this = this;
  70484. if (force === void 0) { force = true; }
  70485. if (force) {
  70486. this._sphere.dispose();
  70487. }
  70488. else {
  70489. setTimeout(function () {
  70490. if (!_this._dataFetched) {
  70491. _this._sphere.dispose();
  70492. }
  70493. }, 0);
  70494. }
  70495. };
  70496. /*** Helpers ***/
  70497. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  70498. if (!this._sphere) {
  70499. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  70500. this._sphere.isVisible = false;
  70501. }
  70502. };
  70503. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  70504. var impostorObject = impostor.object;
  70505. this._prepareSphere();
  70506. this._sphere.position = origin;
  70507. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  70508. this._sphere._updateBoundingInfo();
  70509. this._sphere.computeWorldMatrix(true);
  70510. return this._sphere.intersectsMesh(impostorObject, true);
  70511. };
  70512. return PhysicsRadialExplosionEvent;
  70513. }());
  70514. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  70515. /***** Gravitational Field *****/
  70516. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  70517. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  70518. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70519. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70520. this._physicsHelper = physicsHelper;
  70521. this._scene = scene;
  70522. this._origin = origin;
  70523. this._radius = radius;
  70524. this._strength = strength;
  70525. this._falloff = falloff;
  70526. this._tickCallback = this._tick.bind(this);
  70527. }
  70528. /**
  70529. * Returns the data related to the gravitational field event (sphere).
  70530. * @returns {PhysicsGravitationalFieldEventData}
  70531. */
  70532. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  70533. this._dataFetched = true;
  70534. return {
  70535. sphere: this._sphere,
  70536. };
  70537. };
  70538. /**
  70539. * Enables the gravitational field.
  70540. */
  70541. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  70542. this._tickCallback.call(this);
  70543. this._scene.registerBeforeRender(this._tickCallback);
  70544. };
  70545. /**
  70546. * Disables the gravitational field.
  70547. */
  70548. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  70549. this._scene.unregisterBeforeRender(this._tickCallback);
  70550. };
  70551. /**
  70552. * Disposes the sphere.
  70553. * @param {bolean} force
  70554. */
  70555. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  70556. var _this = this;
  70557. if (force === void 0) { force = true; }
  70558. if (force) {
  70559. this._sphere.dispose();
  70560. }
  70561. else {
  70562. setTimeout(function () {
  70563. if (!_this._dataFetched) {
  70564. _this._sphere.dispose();
  70565. }
  70566. }, 0);
  70567. }
  70568. };
  70569. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  70570. // Since the params won't change, we fetch the event only once
  70571. if (this._sphere) {
  70572. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70573. }
  70574. else {
  70575. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70576. if (radialExplosionEvent) {
  70577. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  70578. }
  70579. }
  70580. };
  70581. return PhysicsGravitationalFieldEvent;
  70582. }());
  70583. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  70584. /***** Updraft *****/
  70585. var PhysicsUpdraftEvent = /** @class */ (function () {
  70586. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  70587. this._scene = _scene;
  70588. this._origin = _origin;
  70589. this._radius = _radius;
  70590. this._strength = _strength;
  70591. this._height = _height;
  70592. this._updraftMode = _updraftMode;
  70593. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70594. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  70595. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70596. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70597. this._physicsEngine = this._scene.getPhysicsEngine();
  70598. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70599. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70600. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70601. this._originDirection = this._origin.subtract(this._originTop).normalize();
  70602. }
  70603. this._tickCallback = this._tick.bind(this);
  70604. }
  70605. /**
  70606. * Returns the data related to the updraft event (cylinder).
  70607. * @returns {PhysicsUpdraftEventData}
  70608. */
  70609. PhysicsUpdraftEvent.prototype.getData = function () {
  70610. this._dataFetched = true;
  70611. return {
  70612. cylinder: this._cylinder,
  70613. };
  70614. };
  70615. /**
  70616. * Enables the updraft.
  70617. */
  70618. PhysicsUpdraftEvent.prototype.enable = function () {
  70619. this._tickCallback.call(this);
  70620. this._scene.registerBeforeRender(this._tickCallback);
  70621. };
  70622. /**
  70623. * Disables the cortex.
  70624. */
  70625. PhysicsUpdraftEvent.prototype.disable = function () {
  70626. this._scene.unregisterBeforeRender(this._tickCallback);
  70627. };
  70628. /**
  70629. * Disposes the sphere.
  70630. * @param {bolean} force
  70631. */
  70632. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  70633. var _this = this;
  70634. if (force === void 0) { force = true; }
  70635. if (force) {
  70636. this._cylinder.dispose();
  70637. }
  70638. else {
  70639. setTimeout(function () {
  70640. if (!_this._dataFetched) {
  70641. _this._cylinder.dispose();
  70642. }
  70643. }, 0);
  70644. }
  70645. };
  70646. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70647. if (impostor.mass === 0) {
  70648. return null;
  70649. }
  70650. if (!this._intersectsWithCylinder(impostor)) {
  70651. return null;
  70652. }
  70653. var impostorObjectCenter = impostor.getObjectCenter();
  70654. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70655. var direction = this._originDirection;
  70656. }
  70657. else {
  70658. var direction = impostorObjectCenter.subtract(this._originTop);
  70659. }
  70660. var multiplier = this._strength * -1;
  70661. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70662. return { force: force, contactPoint: impostorObjectCenter };
  70663. };
  70664. PhysicsUpdraftEvent.prototype._tick = function () {
  70665. var _this = this;
  70666. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70667. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70668. if (!impostorForceAndContactPoint) {
  70669. return;
  70670. }
  70671. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70672. });
  70673. };
  70674. /*** Helpers ***/
  70675. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  70676. if (!this._cylinder) {
  70677. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  70678. height: this._height,
  70679. diameter: this._radius * 2,
  70680. }, this._scene);
  70681. this._cylinder.isVisible = false;
  70682. }
  70683. };
  70684. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  70685. var impostorObject = impostor.object;
  70686. this._prepareCylinder();
  70687. this._cylinder.position = this._cylinderPosition;
  70688. return this._cylinder.intersectsMesh(impostorObject, true);
  70689. };
  70690. return PhysicsUpdraftEvent;
  70691. }());
  70692. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  70693. /***** Vortex *****/
  70694. var PhysicsVortexEvent = /** @class */ (function () {
  70695. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  70696. this._scene = _scene;
  70697. this._origin = _origin;
  70698. this._radius = _radius;
  70699. this._strength = _strength;
  70700. this._height = _height;
  70701. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70702. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  70703. this._updraftMultiplier = 0.02;
  70704. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70705. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70706. this._physicsEngine = this._scene.getPhysicsEngine();
  70707. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70708. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70709. this._tickCallback = this._tick.bind(this);
  70710. }
  70711. /**
  70712. * Returns the data related to the vortex event (cylinder).
  70713. * @returns {PhysicsVortexEventData}
  70714. */
  70715. PhysicsVortexEvent.prototype.getData = function () {
  70716. this._dataFetched = true;
  70717. return {
  70718. cylinder: this._cylinder,
  70719. };
  70720. };
  70721. /**
  70722. * Enables the vortex.
  70723. */
  70724. PhysicsVortexEvent.prototype.enable = function () {
  70725. this._tickCallback.call(this);
  70726. this._scene.registerBeforeRender(this._tickCallback);
  70727. };
  70728. /**
  70729. * Disables the cortex.
  70730. */
  70731. PhysicsVortexEvent.prototype.disable = function () {
  70732. this._scene.unregisterBeforeRender(this._tickCallback);
  70733. };
  70734. /**
  70735. * Disposes the sphere.
  70736. * @param {bolean} force
  70737. */
  70738. PhysicsVortexEvent.prototype.dispose = function (force) {
  70739. var _this = this;
  70740. if (force === void 0) { force = true; }
  70741. if (force) {
  70742. this._cylinder.dispose();
  70743. }
  70744. else {
  70745. setTimeout(function () {
  70746. if (!_this._dataFetched) {
  70747. _this._cylinder.dispose();
  70748. }
  70749. }, 0);
  70750. }
  70751. };
  70752. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70753. if (impostor.mass === 0) {
  70754. return null;
  70755. }
  70756. if (!this._intersectsWithCylinder(impostor)) {
  70757. return null;
  70758. }
  70759. if (impostor.object.getClassName() !== 'Mesh') {
  70760. return null;
  70761. }
  70762. var impostorObject = impostor.object;
  70763. var impostorObjectCenter = impostor.getObjectCenter();
  70764. 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)
  70765. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  70766. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  70767. var hit = ray.intersectsMesh(impostorObject);
  70768. var contactPoint = hit.pickedPoint;
  70769. if (!contactPoint) {
  70770. return null;
  70771. }
  70772. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  70773. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  70774. var directionToOrigin = contactPoint.normalize();
  70775. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70776. directionToOrigin = directionToOrigin.negate();
  70777. }
  70778. // TODO: find a more physically based solution
  70779. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70780. var forceX = directionToOrigin.x * this._strength / 8;
  70781. var forceY = directionToOrigin.y * this._updraftMultiplier;
  70782. var forceZ = directionToOrigin.z * this._strength / 8;
  70783. }
  70784. else {
  70785. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  70786. var forceY = this._originTop.y * this._updraftMultiplier;
  70787. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  70788. }
  70789. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  70790. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  70791. return { force: force, contactPoint: impostorObjectCenter };
  70792. };
  70793. PhysicsVortexEvent.prototype._tick = function () {
  70794. var _this = this;
  70795. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70796. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70797. if (!impostorForceAndContactPoint) {
  70798. return;
  70799. }
  70800. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70801. });
  70802. };
  70803. /*** Helpers ***/
  70804. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  70805. if (!this._cylinder) {
  70806. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  70807. height: this._height,
  70808. diameter: this._radius * 2,
  70809. }, this._scene);
  70810. this._cylinder.isVisible = false;
  70811. }
  70812. };
  70813. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  70814. var impostorObject = impostor.object;
  70815. this._prepareCylinder();
  70816. this._cylinder.position = this._cylinderPosition;
  70817. return this._cylinder.intersectsMesh(impostorObject, true);
  70818. };
  70819. return PhysicsVortexEvent;
  70820. }());
  70821. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  70822. /***** Enums *****/
  70823. /**
  70824. * The strenght of the force in correspondence to the distance of the affected object
  70825. */
  70826. var PhysicsRadialImpulseFalloff;
  70827. (function (PhysicsRadialImpulseFalloff) {
  70828. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  70829. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  70830. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  70831. /**
  70832. * The strenght of the force in correspondence to the distance of the affected object
  70833. */
  70834. var PhysicsUpdraftMode;
  70835. (function (PhysicsUpdraftMode) {
  70836. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  70837. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  70838. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  70839. })(BABYLON || (BABYLON = {}));
  70840. //# sourceMappingURL=babylon.physicsHelper.js.map
  70841. var BABYLON;
  70842. (function (BABYLON) {
  70843. var CannonJSPlugin = /** @class */ (function () {
  70844. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  70845. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  70846. if (iterations === void 0) { iterations = 10; }
  70847. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  70848. this.name = "CannonJSPlugin";
  70849. this._physicsMaterials = new Array();
  70850. this._fixedTimeStep = 1 / 60;
  70851. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  70852. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  70853. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  70854. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  70855. this._tmpPosition = BABYLON.Vector3.Zero();
  70856. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  70857. this._tmpUnityRotation = new BABYLON.Quaternion();
  70858. if (!this.isSupported()) {
  70859. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  70860. return;
  70861. }
  70862. this._extendNamespace();
  70863. this.world = new this.BJSCANNON.World();
  70864. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  70865. this.world.solver.iterations = iterations;
  70866. }
  70867. CannonJSPlugin.prototype.setGravity = function (gravity) {
  70868. this.world.gravity.copy(gravity);
  70869. };
  70870. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  70871. this._fixedTimeStep = timeStep;
  70872. };
  70873. CannonJSPlugin.prototype.getTimeStep = function () {
  70874. return this._fixedTimeStep;
  70875. };
  70876. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  70877. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  70878. };
  70879. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  70880. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  70881. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  70882. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  70883. };
  70884. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  70885. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  70886. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  70887. impostor.physicsBody.applyForce(impulse, worldPoint);
  70888. };
  70889. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  70890. //parent-child relationship. Does this impostor has a parent impostor?
  70891. if (impostor.parent) {
  70892. if (impostor.physicsBody) {
  70893. this.removePhysicsBody(impostor);
  70894. //TODO is that needed?
  70895. impostor.forceUpdate();
  70896. }
  70897. return;
  70898. }
  70899. //should a new body be created for this impostor?
  70900. if (impostor.isBodyInitRequired()) {
  70901. var shape = this._createShape(impostor);
  70902. //unregister events, if body is being changed
  70903. var oldBody = impostor.physicsBody;
  70904. if (oldBody) {
  70905. this.removePhysicsBody(impostor);
  70906. }
  70907. //create the body and material
  70908. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  70909. var bodyCreationObject = {
  70910. mass: impostor.getParam("mass"),
  70911. material: material
  70912. };
  70913. // A simple extend, in case native options were used.
  70914. var nativeOptions = impostor.getParam("nativeOptions");
  70915. for (var key in nativeOptions) {
  70916. if (nativeOptions.hasOwnProperty(key)) {
  70917. bodyCreationObject[key] = nativeOptions[key];
  70918. }
  70919. }
  70920. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  70921. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  70922. this.world.addEventListener("preStep", impostor.beforeStep);
  70923. this.world.addEventListener("postStep", impostor.afterStep);
  70924. impostor.physicsBody.addShape(shape);
  70925. this.world.add(impostor.physicsBody);
  70926. //try to keep the body moving in the right direction by taking old properties.
  70927. //Should be tested!
  70928. if (oldBody) {
  70929. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  70930. impostor.physicsBody[param].copy(oldBody[param]);
  70931. });
  70932. }
  70933. this._processChildMeshes(impostor);
  70934. }
  70935. //now update the body's transformation
  70936. this._updatePhysicsBodyTransformation(impostor);
  70937. };
  70938. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  70939. var _this = this;
  70940. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  70941. var currentRotation = mainImpostor.object.rotationQuaternion;
  70942. if (meshChildren.length) {
  70943. var processMesh = function (localPosition, mesh) {
  70944. if (!currentRotation || !mesh.rotationQuaternion) {
  70945. return;
  70946. }
  70947. var childImpostor = mesh.getPhysicsImpostor();
  70948. if (childImpostor) {
  70949. var parent = childImpostor.parent;
  70950. if (parent !== mainImpostor) {
  70951. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  70952. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  70953. if (childImpostor.physicsBody) {
  70954. _this.removePhysicsBody(childImpostor);
  70955. childImpostor.physicsBody = null;
  70956. }
  70957. childImpostor.parent = mainImpostor;
  70958. childImpostor.resetUpdateFlags();
  70959. 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));
  70960. //Add the mass of the children.
  70961. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  70962. }
  70963. }
  70964. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  70965. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  70966. };
  70967. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  70968. }
  70969. };
  70970. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  70971. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  70972. this.world.removeEventListener("preStep", impostor.beforeStep);
  70973. this.world.removeEventListener("postStep", impostor.afterStep);
  70974. this.world.remove(impostor.physicsBody);
  70975. };
  70976. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  70977. var mainBody = impostorJoint.mainImpostor.physicsBody;
  70978. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  70979. if (!mainBody || !connectedBody) {
  70980. return;
  70981. }
  70982. var constraint;
  70983. var jointData = impostorJoint.joint.jointData;
  70984. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  70985. var constraintData = {
  70986. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  70987. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  70988. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  70989. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  70990. maxForce: jointData.nativeParams.maxForce,
  70991. collideConnected: !!jointData.collision
  70992. };
  70993. switch (impostorJoint.joint.type) {
  70994. case BABYLON.PhysicsJoint.HingeJoint:
  70995. case BABYLON.PhysicsJoint.Hinge2Joint:
  70996. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  70997. break;
  70998. case BABYLON.PhysicsJoint.DistanceJoint:
  70999. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71000. break;
  71001. case BABYLON.PhysicsJoint.SpringJoint:
  71002. var springData = jointData;
  71003. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71004. restLength: springData.length,
  71005. stiffness: springData.stiffness,
  71006. damping: springData.damping,
  71007. localAnchorA: constraintData.pivotA,
  71008. localAnchorB: constraintData.pivotB
  71009. });
  71010. break;
  71011. case BABYLON.PhysicsJoint.LockJoint:
  71012. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71013. break;
  71014. case BABYLON.PhysicsJoint.PointToPointJoint:
  71015. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71016. default:
  71017. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71018. break;
  71019. }
  71020. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71021. constraint.collideConnected = !!jointData.collision;
  71022. impostorJoint.joint.physicsJoint = constraint;
  71023. //don't add spring as constraint, as it is not one.
  71024. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71025. this.world.addConstraint(constraint);
  71026. }
  71027. else {
  71028. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71029. constraint.applyForce();
  71030. });
  71031. }
  71032. };
  71033. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71034. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71035. };
  71036. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71037. var index;
  71038. var mat;
  71039. for (index = 0; index < this._physicsMaterials.length; index++) {
  71040. mat = this._physicsMaterials[index];
  71041. if (mat.friction === friction && mat.restitution === restitution) {
  71042. return mat;
  71043. }
  71044. }
  71045. var currentMat = new this.BJSCANNON.Material(name);
  71046. currentMat.friction = friction;
  71047. currentMat.restitution = restitution;
  71048. this._physicsMaterials.push(currentMat);
  71049. return currentMat;
  71050. };
  71051. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71052. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71053. };
  71054. CannonJSPlugin.prototype._createShape = function (impostor) {
  71055. var object = impostor.object;
  71056. var returnValue;
  71057. var extendSize = impostor.getObjectExtendSize();
  71058. switch (impostor.type) {
  71059. case BABYLON.PhysicsImpostor.SphereImpostor:
  71060. var radiusX = extendSize.x;
  71061. var radiusY = extendSize.y;
  71062. var radiusZ = extendSize.z;
  71063. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71064. break;
  71065. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71066. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71067. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71068. break;
  71069. case BABYLON.PhysicsImpostor.BoxImpostor:
  71070. var box = extendSize.scale(0.5);
  71071. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71072. break;
  71073. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71074. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71075. returnValue = new this.BJSCANNON.Plane();
  71076. break;
  71077. case BABYLON.PhysicsImpostor.MeshImpostor:
  71078. // should transform the vertex data to world coordinates!!
  71079. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71080. var rawFaces = object.getIndices ? object.getIndices() : [];
  71081. if (!rawVerts)
  71082. return;
  71083. // get only scale! so the object could transform correctly.
  71084. var oldPosition = object.position.clone();
  71085. var oldRotation = object.rotation && object.rotation.clone();
  71086. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71087. object.position.copyFromFloats(0, 0, 0);
  71088. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71089. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71090. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71091. var transform = object.computeWorldMatrix(true);
  71092. // convert rawVerts to object space
  71093. var temp = new Array();
  71094. var index;
  71095. for (index = 0; index < rawVerts.length; index += 3) {
  71096. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71097. }
  71098. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71099. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71100. //now set back the transformation!
  71101. object.position.copyFrom(oldPosition);
  71102. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71103. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71104. break;
  71105. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71106. var oldPosition2 = object.position.clone();
  71107. var oldRotation2 = object.rotation && object.rotation.clone();
  71108. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71109. object.position.copyFromFloats(0, 0, 0);
  71110. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71111. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71112. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71113. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71114. returnValue = this._createHeightmap(object);
  71115. object.position.copyFrom(oldPosition2);
  71116. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71117. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71118. object.computeWorldMatrix(true);
  71119. break;
  71120. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71121. returnValue = new this.BJSCANNON.Particle();
  71122. break;
  71123. }
  71124. return returnValue;
  71125. };
  71126. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71127. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71128. var transform = object.computeWorldMatrix(true);
  71129. // convert rawVerts to object space
  71130. var temp = new Array();
  71131. var index;
  71132. for (index = 0; index < pos.length; index += 3) {
  71133. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71134. }
  71135. pos = temp;
  71136. var matrix = new Array();
  71137. //For now pointDepth will not be used and will be automatically calculated.
  71138. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71139. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71140. var boundingInfo = object.getBoundingInfo();
  71141. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71142. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71143. var elementSize = dim * 2 / arraySize;
  71144. for (var i = 0; i < pos.length; i = i + 3) {
  71145. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71146. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71147. var y = -pos[i + 2] + minY;
  71148. if (!matrix[x]) {
  71149. matrix[x] = [];
  71150. }
  71151. if (!matrix[x][z]) {
  71152. matrix[x][z] = y;
  71153. }
  71154. matrix[x][z] = Math.max(y, matrix[x][z]);
  71155. }
  71156. for (var x = 0; x <= arraySize; ++x) {
  71157. if (!matrix[x]) {
  71158. var loc = 1;
  71159. while (!matrix[(x + loc) % arraySize]) {
  71160. loc++;
  71161. }
  71162. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71163. //console.log("missing x", x);
  71164. }
  71165. for (var z = 0; z <= arraySize; ++z) {
  71166. if (!matrix[x][z]) {
  71167. var loc = 1;
  71168. var newValue;
  71169. while (newValue === undefined) {
  71170. newValue = matrix[x][(z + loc++) % arraySize];
  71171. }
  71172. matrix[x][z] = newValue;
  71173. }
  71174. }
  71175. }
  71176. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71177. elementSize: elementSize
  71178. });
  71179. //For future reference, needed for body transformation
  71180. shape.minY = minY;
  71181. return shape;
  71182. };
  71183. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71184. var object = impostor.object;
  71185. //make sure it is updated...
  71186. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71187. // The delta between the mesh position and the mesh bounding box center
  71188. var bInfo = object.getBoundingInfo();
  71189. if (!bInfo)
  71190. return;
  71191. var center = impostor.getObjectCenter();
  71192. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71193. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71194. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71195. this._tmpPosition.copyFrom(center);
  71196. var quaternion = object.rotationQuaternion;
  71197. if (!quaternion) {
  71198. return;
  71199. }
  71200. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71201. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71202. //-90 DEG in X, precalculated
  71203. quaternion = quaternion.multiply(this._minus90X);
  71204. //Invert! (Precalculated, 90 deg in X)
  71205. //No need to clone. this will never change.
  71206. impostor.setDeltaRotation(this._plus90X);
  71207. }
  71208. //If it is a heightfield, if should be centered.
  71209. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71210. var mesh = object;
  71211. var boundingInfo = mesh.getBoundingInfo();
  71212. //calculate the correct body position:
  71213. var rotationQuaternion = mesh.rotationQuaternion;
  71214. mesh.rotationQuaternion = this._tmpUnityRotation;
  71215. mesh.computeWorldMatrix(true);
  71216. //get original center with no rotation
  71217. var c = center.clone();
  71218. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71219. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71220. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71221. mesh.setPivotMatrix(p);
  71222. mesh.computeWorldMatrix(true);
  71223. //calculate the translation
  71224. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71225. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71226. //add it inverted to the delta
  71227. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71228. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71229. //rotation is back
  71230. mesh.rotationQuaternion = rotationQuaternion;
  71231. mesh.setPivotMatrix(oldPivot);
  71232. mesh.computeWorldMatrix(true);
  71233. }
  71234. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71235. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71236. //this._tmpPosition.copyFrom(object.position);
  71237. }
  71238. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71239. //Now update the impostor object
  71240. impostor.physicsBody.position.copy(this._tmpPosition);
  71241. impostor.physicsBody.quaternion.copy(quaternion);
  71242. };
  71243. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71244. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71245. if (impostor.object.rotationQuaternion) {
  71246. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71247. }
  71248. };
  71249. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71250. impostor.physicsBody.position.copy(newPosition);
  71251. impostor.physicsBody.quaternion.copy(newRotation);
  71252. };
  71253. CannonJSPlugin.prototype.isSupported = function () {
  71254. return this.BJSCANNON !== undefined;
  71255. };
  71256. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71257. impostor.physicsBody.velocity.copy(velocity);
  71258. };
  71259. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71260. impostor.physicsBody.angularVelocity.copy(velocity);
  71261. };
  71262. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71263. var v = impostor.physicsBody.velocity;
  71264. if (!v) {
  71265. return null;
  71266. }
  71267. return new BABYLON.Vector3(v.x, v.y, v.z);
  71268. };
  71269. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71270. var v = impostor.physicsBody.angularVelocity;
  71271. if (!v) {
  71272. return null;
  71273. }
  71274. return new BABYLON.Vector3(v.x, v.y, v.z);
  71275. };
  71276. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71277. impostor.physicsBody.mass = mass;
  71278. impostor.physicsBody.updateMassProperties();
  71279. };
  71280. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71281. return impostor.physicsBody.mass;
  71282. };
  71283. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71284. return impostor.physicsBody.material.friction;
  71285. };
  71286. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71287. impostor.physicsBody.material.friction = friction;
  71288. };
  71289. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71290. return impostor.physicsBody.material.restitution;
  71291. };
  71292. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71293. impostor.physicsBody.material.restitution = restitution;
  71294. };
  71295. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71296. impostor.physicsBody.sleep();
  71297. };
  71298. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71299. impostor.physicsBody.wakeUp();
  71300. };
  71301. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71302. joint.physicsJoint.distance = maxDistance;
  71303. };
  71304. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71305. // if (!motorIndex) {
  71306. // joint.physicsJoint.enableMotor();
  71307. // }
  71308. // }
  71309. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71310. // if (!motorIndex) {
  71311. // joint.physicsJoint.disableMotor();
  71312. // }
  71313. // }
  71314. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71315. if (!motorIndex) {
  71316. joint.physicsJoint.enableMotor();
  71317. joint.physicsJoint.setMotorSpeed(speed);
  71318. if (maxForce) {
  71319. this.setLimit(joint, maxForce);
  71320. }
  71321. }
  71322. };
  71323. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71324. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71325. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71326. };
  71327. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71328. var body = impostor.physicsBody;
  71329. mesh.position.x = body.position.x;
  71330. mesh.position.y = body.position.y;
  71331. mesh.position.z = body.position.z;
  71332. if (mesh.rotationQuaternion) {
  71333. mesh.rotationQuaternion.x = body.quaternion.x;
  71334. mesh.rotationQuaternion.y = body.quaternion.y;
  71335. mesh.rotationQuaternion.z = body.quaternion.z;
  71336. mesh.rotationQuaternion.w = body.quaternion.w;
  71337. }
  71338. };
  71339. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71340. var shape = impostor.physicsBody.shapes[0];
  71341. return shape.boundingSphereRadius;
  71342. };
  71343. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71344. var shape = impostor.physicsBody.shapes[0];
  71345. result.x = shape.halfExtents.x * 2;
  71346. result.y = shape.halfExtents.y * 2;
  71347. result.z = shape.halfExtents.z * 2;
  71348. };
  71349. CannonJSPlugin.prototype.dispose = function () {
  71350. };
  71351. CannonJSPlugin.prototype._extendNamespace = function () {
  71352. //this will force cannon to execute at least one step when using interpolation
  71353. var step_tmp1 = new this.BJSCANNON.Vec3();
  71354. var Engine = this.BJSCANNON;
  71355. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71356. maxSubSteps = maxSubSteps || 10;
  71357. timeSinceLastCalled = timeSinceLastCalled || 0;
  71358. if (timeSinceLastCalled === 0) {
  71359. this.internalStep(dt);
  71360. this.time += dt;
  71361. }
  71362. else {
  71363. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71364. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71365. var t0 = performance.now();
  71366. for (var i = 0; i !== internalSteps; i++) {
  71367. this.internalStep(dt);
  71368. if (performance.now() - t0 > dt * 1000) {
  71369. break;
  71370. }
  71371. }
  71372. this.time += timeSinceLastCalled;
  71373. var h = this.time % dt;
  71374. var h_div_dt = h / dt;
  71375. var interpvelo = step_tmp1;
  71376. var bodies = this.bodies;
  71377. for (var j = 0; j !== bodies.length; j++) {
  71378. var b = bodies[j];
  71379. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71380. b.position.vsub(b.previousPosition, interpvelo);
  71381. interpvelo.scale(h_div_dt, interpvelo);
  71382. b.position.vadd(interpvelo, b.interpolatedPosition);
  71383. }
  71384. else {
  71385. b.interpolatedPosition.copy(b.position);
  71386. b.interpolatedQuaternion.copy(b.quaternion);
  71387. }
  71388. }
  71389. }
  71390. };
  71391. };
  71392. return CannonJSPlugin;
  71393. }());
  71394. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71395. })(BABYLON || (BABYLON = {}));
  71396. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71397. var BABYLON;
  71398. (function (BABYLON) {
  71399. var OimoJSPlugin = /** @class */ (function () {
  71400. function OimoJSPlugin(iterations) {
  71401. this.name = "OimoJSPlugin";
  71402. this._tmpImpostorsArray = [];
  71403. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71404. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71405. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71406. this.world.worldscale(1);
  71407. this.world.clear();
  71408. //making sure no stats are calculated
  71409. this.world.isNoStat = true;
  71410. }
  71411. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71412. this.world.gravity.copy(gravity);
  71413. };
  71414. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71415. this.world.timeStep = timeStep;
  71416. };
  71417. OimoJSPlugin.prototype.getTimeStep = function () {
  71418. return this.world.timeStep;
  71419. };
  71420. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71421. var _this = this;
  71422. impostors.forEach(function (impostor) {
  71423. impostor.beforeStep();
  71424. });
  71425. this.world.step();
  71426. impostors.forEach(function (impostor) {
  71427. impostor.afterStep();
  71428. //update the ordered impostors array
  71429. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71430. });
  71431. //check for collisions
  71432. var contact = this.world.contacts;
  71433. while (contact !== null) {
  71434. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71435. contact = contact.next;
  71436. continue;
  71437. }
  71438. //is this body colliding with any other? get the impostor
  71439. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71440. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71441. if (!mainImpostor || !collidingImpostor) {
  71442. contact = contact.next;
  71443. continue;
  71444. }
  71445. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71446. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71447. contact = contact.next;
  71448. }
  71449. };
  71450. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71451. var mass = impostor.physicsBody.massInfo.mass;
  71452. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71453. };
  71454. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71455. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71456. this.applyImpulse(impostor, force, contactPoint);
  71457. };
  71458. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71459. var _this = this;
  71460. //parent-child relationship. Does this impostor has a parent impostor?
  71461. if (impostor.parent) {
  71462. if (impostor.physicsBody) {
  71463. this.removePhysicsBody(impostor);
  71464. //TODO is that needed?
  71465. impostor.forceUpdate();
  71466. }
  71467. return;
  71468. }
  71469. if (impostor.isBodyInitRequired()) {
  71470. var bodyConfig = {
  71471. name: impostor.uniqueId,
  71472. //Oimo must have mass, also for static objects.
  71473. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  71474. size: [],
  71475. type: [],
  71476. pos: [],
  71477. rot: [],
  71478. move: impostor.getParam("mass") !== 0,
  71479. //Supporting older versions of Oimo
  71480. world: this.world
  71481. };
  71482. var impostors = [impostor];
  71483. var addToArray = function (parent) {
  71484. if (!parent.getChildMeshes)
  71485. return;
  71486. parent.getChildMeshes().forEach(function (m) {
  71487. if (m.physicsImpostor) {
  71488. impostors.push(m.physicsImpostor);
  71489. //m.physicsImpostor._init();
  71490. }
  71491. });
  71492. };
  71493. addToArray(impostor.object);
  71494. var checkWithEpsilon_1 = function (value) {
  71495. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  71496. };
  71497. impostors.forEach(function (i) {
  71498. if (!impostor.object.rotationQuaternion) {
  71499. return;
  71500. }
  71501. //get the correct bounding box
  71502. var oldQuaternion = i.object.rotationQuaternion;
  71503. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  71504. x: impostor.object.rotationQuaternion.x,
  71505. y: impostor.object.rotationQuaternion.y,
  71506. z: impostor.object.rotationQuaternion.z,
  71507. s: impostor.object.rotationQuaternion.w
  71508. });
  71509. var extendSize = i.getObjectExtendSize();
  71510. if (i === impostor) {
  71511. var center = impostor.getObjectCenter();
  71512. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  71513. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  71514. //Can also use Array.prototype.push.apply
  71515. bodyConfig.pos.push(center.x);
  71516. bodyConfig.pos.push(center.y);
  71517. bodyConfig.pos.push(center.z);
  71518. //tmp solution
  71519. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71520. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71521. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71522. }
  71523. else {
  71524. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  71525. bodyConfig.pos.push(localPosition.x);
  71526. bodyConfig.pos.push(localPosition.y);
  71527. bodyConfig.pos.push(localPosition.z);
  71528. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  71529. bodyConfig.rot.push(0);
  71530. bodyConfig.rot.push(0);
  71531. bodyConfig.rot.push(0);
  71532. }
  71533. // register mesh
  71534. switch (i.type) {
  71535. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71536. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  71537. case BABYLON.PhysicsImpostor.SphereImpostor:
  71538. var radiusX = extendSize.x;
  71539. var radiusY = extendSize.y;
  71540. var radiusZ = extendSize.z;
  71541. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  71542. bodyConfig.type.push('sphere');
  71543. //due to the way oimo works with compounds, add 3 times
  71544. bodyConfig.size.push(size);
  71545. bodyConfig.size.push(size);
  71546. bodyConfig.size.push(size);
  71547. break;
  71548. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71549. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  71550. var sizeY = checkWithEpsilon_1(extendSize.y);
  71551. bodyConfig.type.push('cylinder');
  71552. bodyConfig.size.push(sizeX);
  71553. bodyConfig.size.push(sizeY);
  71554. //due to the way oimo works with compounds, add one more value.
  71555. bodyConfig.size.push(sizeY);
  71556. break;
  71557. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71558. case BABYLON.PhysicsImpostor.BoxImpostor:
  71559. default:
  71560. var sizeX = checkWithEpsilon_1(extendSize.x);
  71561. var sizeY = checkWithEpsilon_1(extendSize.y);
  71562. var sizeZ = checkWithEpsilon_1(extendSize.z);
  71563. bodyConfig.type.push('box');
  71564. bodyConfig.size.push(sizeX);
  71565. bodyConfig.size.push(sizeY);
  71566. bodyConfig.size.push(sizeZ);
  71567. break;
  71568. }
  71569. //actually not needed, but hey...
  71570. i.object.rotationQuaternion = oldQuaternion;
  71571. });
  71572. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  71573. }
  71574. else {
  71575. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  71576. }
  71577. impostor.setDeltaPosition(this._tmpPositionVector);
  71578. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  71579. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  71580. };
  71581. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71582. //impostor.physicsBody.dispose();
  71583. //Same as : (older oimo versions)
  71584. this.world.removeRigidBody(impostor.physicsBody);
  71585. };
  71586. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71587. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71588. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71589. if (!mainBody || !connectedBody) {
  71590. return;
  71591. }
  71592. var jointData = impostorJoint.joint.jointData;
  71593. var options = jointData.nativeParams || {};
  71594. var type;
  71595. var nativeJointData = {
  71596. body1: mainBody,
  71597. body2: connectedBody,
  71598. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  71599. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  71600. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  71601. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  71602. min: options.min,
  71603. max: options.max,
  71604. collision: options.collision || jointData.collision,
  71605. spring: options.spring,
  71606. //supporting older version of Oimo
  71607. world: this.world
  71608. };
  71609. switch (impostorJoint.joint.type) {
  71610. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71611. type = "jointBall";
  71612. break;
  71613. case BABYLON.PhysicsJoint.SpringJoint:
  71614. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  71615. var springData = jointData;
  71616. nativeJointData.min = springData.length || nativeJointData.min;
  71617. //Max should also be set, just make sure it is at least min
  71618. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  71619. case BABYLON.PhysicsJoint.DistanceJoint:
  71620. type = "jointDistance";
  71621. nativeJointData.max = jointData.maxDistance;
  71622. break;
  71623. case BABYLON.PhysicsJoint.PrismaticJoint:
  71624. type = "jointPrisme";
  71625. break;
  71626. case BABYLON.PhysicsJoint.SliderJoint:
  71627. type = "jointSlide";
  71628. break;
  71629. case BABYLON.PhysicsJoint.WheelJoint:
  71630. type = "jointWheel";
  71631. break;
  71632. case BABYLON.PhysicsJoint.HingeJoint:
  71633. default:
  71634. type = "jointHinge";
  71635. break;
  71636. }
  71637. nativeJointData.type = type;
  71638. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  71639. };
  71640. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71641. //Bug in Oimo prevents us from disposing a joint in the playground
  71642. //joint.joint.physicsJoint.dispose();
  71643. //So we will bruteforce it!
  71644. try {
  71645. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  71646. }
  71647. catch (e) {
  71648. BABYLON.Tools.Warn(e);
  71649. }
  71650. };
  71651. OimoJSPlugin.prototype.isSupported = function () {
  71652. return this.BJSOIMO !== undefined;
  71653. };
  71654. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71655. if (!impostor.physicsBody.sleeping) {
  71656. //TODO check that
  71657. if (impostor.physicsBody.shapes.next) {
  71658. var parentShape = this._getLastShape(impostor.physicsBody);
  71659. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  71660. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  71661. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  71662. }
  71663. else {
  71664. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  71665. }
  71666. if (impostor.object.rotationQuaternion) {
  71667. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  71668. impostor.object.rotationQuaternion.normalize();
  71669. }
  71670. }
  71671. };
  71672. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71673. var body = impostor.physicsBody;
  71674. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  71675. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  71676. body.syncShapes();
  71677. body.awake();
  71678. };
  71679. OimoJSPlugin.prototype._getLastShape = function (body) {
  71680. var lastShape = body.shapes;
  71681. while (lastShape.next) {
  71682. lastShape = lastShape.next;
  71683. }
  71684. return lastShape;
  71685. };
  71686. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71687. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  71688. };
  71689. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71690. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  71691. };
  71692. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71693. var v = impostor.physicsBody.linearVelocity;
  71694. if (!v) {
  71695. return null;
  71696. }
  71697. return new BABYLON.Vector3(v.x, v.y, v.z);
  71698. };
  71699. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71700. var v = impostor.physicsBody.angularVelocity;
  71701. if (!v) {
  71702. return null;
  71703. }
  71704. return new BABYLON.Vector3(v.x, v.y, v.z);
  71705. };
  71706. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71707. var staticBody = mass === 0;
  71708. //this will actually set the body's density and not its mass.
  71709. //But this is how oimo treats the mass variable.
  71710. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  71711. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  71712. };
  71713. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  71714. return impostor.physicsBody.shapes.density;
  71715. };
  71716. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  71717. return impostor.physicsBody.shapes.friction;
  71718. };
  71719. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71720. impostor.physicsBody.shapes.friction = friction;
  71721. };
  71722. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71723. return impostor.physicsBody.shapes.restitution;
  71724. };
  71725. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71726. impostor.physicsBody.shapes.restitution = restitution;
  71727. };
  71728. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  71729. impostor.physicsBody.sleep();
  71730. };
  71731. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  71732. impostor.physicsBody.awake();
  71733. };
  71734. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71735. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  71736. if (minDistance !== void 0) {
  71737. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  71738. }
  71739. };
  71740. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71741. //TODO separate rotational and transational motors.
  71742. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71743. if (motor) {
  71744. motor.setMotor(speed, maxForce);
  71745. }
  71746. };
  71747. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  71748. //TODO separate rotational and transational motors.
  71749. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71750. if (motor) {
  71751. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  71752. }
  71753. };
  71754. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71755. var body = impostor.physicsBody;
  71756. mesh.position.x = body.position.x;
  71757. mesh.position.y = body.position.y;
  71758. mesh.position.z = body.position.z;
  71759. if (mesh.rotationQuaternion) {
  71760. mesh.rotationQuaternion.x = body.orientation.x;
  71761. mesh.rotationQuaternion.y = body.orientation.y;
  71762. mesh.rotationQuaternion.z = body.orientation.z;
  71763. mesh.rotationQuaternion.w = body.orientation.s;
  71764. }
  71765. };
  71766. OimoJSPlugin.prototype.getRadius = function (impostor) {
  71767. return impostor.physicsBody.shapes.radius;
  71768. };
  71769. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71770. var shape = impostor.physicsBody.shapes;
  71771. result.x = shape.halfWidth * 2;
  71772. result.y = shape.halfHeight * 2;
  71773. result.z = shape.halfDepth * 2;
  71774. };
  71775. OimoJSPlugin.prototype.dispose = function () {
  71776. this.world.clear();
  71777. };
  71778. return OimoJSPlugin;
  71779. }());
  71780. BABYLON.OimoJSPlugin = OimoJSPlugin;
  71781. })(BABYLON || (BABYLON = {}));
  71782. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  71783. var BABYLON;
  71784. (function (BABYLON) {
  71785. /*
  71786. * Based on jsTGALoader - Javascript loader for TGA file
  71787. * By Vincent Thibault
  71788. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  71789. */
  71790. var TGATools = /** @class */ (function () {
  71791. function TGATools() {
  71792. }
  71793. TGATools.GetTGAHeader = function (data) {
  71794. var offset = 0;
  71795. var header = {
  71796. id_length: data[offset++],
  71797. colormap_type: data[offset++],
  71798. image_type: data[offset++],
  71799. colormap_index: data[offset++] | data[offset++] << 8,
  71800. colormap_length: data[offset++] | data[offset++] << 8,
  71801. colormap_size: data[offset++],
  71802. origin: [
  71803. data[offset++] | data[offset++] << 8,
  71804. data[offset++] | data[offset++] << 8
  71805. ],
  71806. width: data[offset++] | data[offset++] << 8,
  71807. height: data[offset++] | data[offset++] << 8,
  71808. pixel_size: data[offset++],
  71809. flags: data[offset++]
  71810. };
  71811. return header;
  71812. };
  71813. TGATools.UploadContent = function (gl, data) {
  71814. // Not enough data to contain header ?
  71815. if (data.length < 19) {
  71816. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  71817. return;
  71818. }
  71819. // Read Header
  71820. var offset = 18;
  71821. var header = TGATools.GetTGAHeader(data);
  71822. // Assume it's a valid Targa file.
  71823. if (header.id_length + offset > data.length) {
  71824. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  71825. return;
  71826. }
  71827. // Skip not needed data
  71828. offset += header.id_length;
  71829. var use_rle = false;
  71830. var use_pal = false;
  71831. var use_grey = false;
  71832. // Get some informations.
  71833. switch (header.image_type) {
  71834. case TGATools._TYPE_RLE_INDEXED:
  71835. use_rle = true;
  71836. case TGATools._TYPE_INDEXED:
  71837. use_pal = true;
  71838. break;
  71839. case TGATools._TYPE_RLE_RGB:
  71840. use_rle = true;
  71841. case TGATools._TYPE_RGB:
  71842. // use_rgb = true;
  71843. break;
  71844. case TGATools._TYPE_RLE_GREY:
  71845. use_rle = true;
  71846. case TGATools._TYPE_GREY:
  71847. use_grey = true;
  71848. break;
  71849. }
  71850. var pixel_data;
  71851. // var numAlphaBits = header.flags & 0xf;
  71852. var pixel_size = header.pixel_size >> 3;
  71853. var pixel_total = header.width * header.height * pixel_size;
  71854. // Read palettes
  71855. var palettes;
  71856. if (use_pal) {
  71857. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  71858. }
  71859. // Read LRE
  71860. if (use_rle) {
  71861. pixel_data = new Uint8Array(pixel_total);
  71862. var c, count, i;
  71863. var localOffset = 0;
  71864. var pixels = new Uint8Array(pixel_size);
  71865. while (offset < pixel_total && localOffset < pixel_total) {
  71866. c = data[offset++];
  71867. count = (c & 0x7f) + 1;
  71868. // RLE pixels
  71869. if (c & 0x80) {
  71870. // Bind pixel tmp array
  71871. for (i = 0; i < pixel_size; ++i) {
  71872. pixels[i] = data[offset++];
  71873. }
  71874. // Copy pixel array
  71875. for (i = 0; i < count; ++i) {
  71876. pixel_data.set(pixels, localOffset + i * pixel_size);
  71877. }
  71878. localOffset += pixel_size * count;
  71879. }
  71880. else {
  71881. count *= pixel_size;
  71882. for (i = 0; i < count; ++i) {
  71883. pixel_data[localOffset + i] = data[offset++];
  71884. }
  71885. localOffset += count;
  71886. }
  71887. }
  71888. }
  71889. else {
  71890. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  71891. }
  71892. // Load to texture
  71893. var x_start, y_start, x_step, y_step, y_end, x_end;
  71894. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  71895. default:
  71896. case TGATools._ORIGIN_UL:
  71897. x_start = 0;
  71898. x_step = 1;
  71899. x_end = header.width;
  71900. y_start = 0;
  71901. y_step = 1;
  71902. y_end = header.height;
  71903. break;
  71904. case TGATools._ORIGIN_BL:
  71905. x_start = 0;
  71906. x_step = 1;
  71907. x_end = header.width;
  71908. y_start = header.height - 1;
  71909. y_step = -1;
  71910. y_end = -1;
  71911. break;
  71912. case TGATools._ORIGIN_UR:
  71913. x_start = header.width - 1;
  71914. x_step = -1;
  71915. x_end = -1;
  71916. y_start = 0;
  71917. y_step = 1;
  71918. y_end = header.height;
  71919. break;
  71920. case TGATools._ORIGIN_BR:
  71921. x_start = header.width - 1;
  71922. x_step = -1;
  71923. x_end = -1;
  71924. y_start = header.height - 1;
  71925. y_step = -1;
  71926. y_end = -1;
  71927. break;
  71928. }
  71929. // Load the specify method
  71930. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  71931. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  71932. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  71933. };
  71934. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71935. var image = pixel_data, colormap = palettes;
  71936. var width = header.width, height = header.height;
  71937. var color, i = 0, x, y;
  71938. var imageData = new Uint8Array(width * height * 4);
  71939. for (y = y_start; y !== y_end; y += y_step) {
  71940. for (x = x_start; x !== x_end; x += x_step, i++) {
  71941. color = image[i];
  71942. imageData[(x + width * y) * 4 + 3] = 255;
  71943. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  71944. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  71945. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  71946. }
  71947. }
  71948. return imageData;
  71949. };
  71950. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71951. var image = pixel_data;
  71952. var width = header.width, height = header.height;
  71953. var color, i = 0, x, y;
  71954. var imageData = new Uint8Array(width * height * 4);
  71955. for (y = y_start; y !== y_end; y += y_step) {
  71956. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  71957. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  71958. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  71959. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  71960. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  71961. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  71962. }
  71963. }
  71964. return imageData;
  71965. };
  71966. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71967. var image = pixel_data;
  71968. var width = header.width, height = header.height;
  71969. var i = 0, x, y;
  71970. var imageData = new Uint8Array(width * height * 4);
  71971. for (y = y_start; y !== y_end; y += y_step) {
  71972. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  71973. imageData[(x + width * y) * 4 + 3] = 255;
  71974. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  71975. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  71976. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  71977. }
  71978. }
  71979. return imageData;
  71980. };
  71981. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71982. var image = pixel_data;
  71983. var width = header.width, height = header.height;
  71984. var i = 0, x, y;
  71985. var imageData = new Uint8Array(width * height * 4);
  71986. for (y = y_start; y !== y_end; y += y_step) {
  71987. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  71988. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  71989. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  71990. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  71991. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  71992. }
  71993. }
  71994. return imageData;
  71995. };
  71996. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71997. var image = pixel_data;
  71998. var width = header.width, height = header.height;
  71999. var color, i = 0, x, y;
  72000. var imageData = new Uint8Array(width * height * 4);
  72001. for (y = y_start; y !== y_end; y += y_step) {
  72002. for (x = x_start; x !== x_end; x += x_step, i++) {
  72003. color = image[i];
  72004. imageData[(x + width * y) * 4 + 0] = color;
  72005. imageData[(x + width * y) * 4 + 1] = color;
  72006. imageData[(x + width * y) * 4 + 2] = color;
  72007. imageData[(x + width * y) * 4 + 3] = 255;
  72008. }
  72009. }
  72010. return imageData;
  72011. };
  72012. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72013. var image = pixel_data;
  72014. var width = header.width, height = header.height;
  72015. var i = 0, x, y;
  72016. var imageData = new Uint8Array(width * height * 4);
  72017. for (y = y_start; y !== y_end; y += y_step) {
  72018. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72019. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72020. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72021. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72022. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72023. }
  72024. }
  72025. return imageData;
  72026. };
  72027. //private static _TYPE_NO_DATA = 0;
  72028. TGATools._TYPE_INDEXED = 1;
  72029. TGATools._TYPE_RGB = 2;
  72030. TGATools._TYPE_GREY = 3;
  72031. TGATools._TYPE_RLE_INDEXED = 9;
  72032. TGATools._TYPE_RLE_RGB = 10;
  72033. TGATools._TYPE_RLE_GREY = 11;
  72034. TGATools._ORIGIN_MASK = 0x30;
  72035. TGATools._ORIGIN_SHIFT = 0x04;
  72036. TGATools._ORIGIN_BL = 0x00;
  72037. TGATools._ORIGIN_BR = 0x01;
  72038. TGATools._ORIGIN_UL = 0x02;
  72039. TGATools._ORIGIN_UR = 0x03;
  72040. return TGATools;
  72041. }());
  72042. BABYLON.TGATools = TGATools;
  72043. })(BABYLON || (BABYLON = {}));
  72044. //# sourceMappingURL=babylon.tga.js.map
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72048. // All values and structures referenced from:
  72049. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72050. var DDS_MAGIC = 0x20534444;
  72051. var
  72052. //DDSD_CAPS = 0x1,
  72053. //DDSD_HEIGHT = 0x2,
  72054. //DDSD_WIDTH = 0x4,
  72055. //DDSD_PITCH = 0x8,
  72056. //DDSD_PIXELFORMAT = 0x1000,
  72057. DDSD_MIPMAPCOUNT = 0x20000;
  72058. //DDSD_LINEARSIZE = 0x80000,
  72059. //DDSD_DEPTH = 0x800000;
  72060. // var DDSCAPS_COMPLEX = 0x8,
  72061. // DDSCAPS_MIPMAP = 0x400000,
  72062. // DDSCAPS_TEXTURE = 0x1000;
  72063. var DDSCAPS2_CUBEMAP = 0x200;
  72064. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72065. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72066. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72067. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72068. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72069. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72070. // DDSCAPS2_VOLUME = 0x200000;
  72071. var
  72072. //DDPF_ALPHAPIXELS = 0x1,
  72073. //DDPF_ALPHA = 0x2,
  72074. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72075. //DDPF_YUV = 0x200,
  72076. DDPF_LUMINANCE = 0x20000;
  72077. function FourCCToInt32(value) {
  72078. return value.charCodeAt(0) +
  72079. (value.charCodeAt(1) << 8) +
  72080. (value.charCodeAt(2) << 16) +
  72081. (value.charCodeAt(3) << 24);
  72082. }
  72083. function Int32ToFourCC(value) {
  72084. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72085. }
  72086. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72087. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72088. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72089. var FOURCC_DX10 = FourCCToInt32("DX10");
  72090. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72091. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72092. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72093. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72094. var headerLengthInt = 31; // The header length in 32 bit ints
  72095. // Offsets into the header array
  72096. var off_magic = 0;
  72097. var off_size = 1;
  72098. var off_flags = 2;
  72099. var off_height = 3;
  72100. var off_width = 4;
  72101. var off_mipmapCount = 7;
  72102. var off_pfFlags = 20;
  72103. var off_pfFourCC = 21;
  72104. var off_RGBbpp = 22;
  72105. var off_RMask = 23;
  72106. var off_GMask = 24;
  72107. var off_BMask = 25;
  72108. var off_AMask = 26;
  72109. // var off_caps1 = 27;
  72110. var off_caps2 = 28;
  72111. // var off_caps3 = 29;
  72112. // var off_caps4 = 30;
  72113. var off_dxgiFormat = 32;
  72114. ;
  72115. var DDSTools = /** @class */ (function () {
  72116. function DDSTools() {
  72117. }
  72118. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72119. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72120. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72121. var mipmapCount = 1;
  72122. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72123. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72124. }
  72125. var fourCC = header[off_pfFourCC];
  72126. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72127. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72128. switch (fourCC) {
  72129. case FOURCC_D3DFMT_R16G16B16A16F:
  72130. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72131. break;
  72132. case FOURCC_D3DFMT_R32G32B32A32F:
  72133. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72134. break;
  72135. case FOURCC_DX10:
  72136. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72137. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72138. break;
  72139. }
  72140. }
  72141. return {
  72142. width: header[off_width],
  72143. height: header[off_height],
  72144. mipmapCount: mipmapCount,
  72145. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72146. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72147. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72148. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72149. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72150. dxgiFormat: dxgiFormat,
  72151. textureType: textureType
  72152. };
  72153. };
  72154. DDSTools._ToHalfFloat = function (value) {
  72155. if (!DDSTools._FloatView) {
  72156. DDSTools._FloatView = new Float32Array(1);
  72157. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72158. }
  72159. DDSTools._FloatView[0] = value;
  72160. var x = DDSTools._Int32View[0];
  72161. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72162. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72163. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72164. /* If zero, or denormal, or exponent underflows too much for a denormal
  72165. * half, return signed zero. */
  72166. if (e < 103) {
  72167. return bits;
  72168. }
  72169. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72170. if (e > 142) {
  72171. bits |= 0x7c00;
  72172. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72173. * not Inf, so make sure we set one mantissa bit too. */
  72174. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72175. return bits;
  72176. }
  72177. /* If exponent underflows but not too much, return a denormal */
  72178. if (e < 113) {
  72179. m |= 0x0800;
  72180. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72181. * to 1, which is OK. */
  72182. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72183. return bits;
  72184. }
  72185. bits |= ((e - 112) << 10) | (m >> 1);
  72186. bits += m & 1;
  72187. return bits;
  72188. };
  72189. DDSTools._FromHalfFloat = function (value) {
  72190. var s = (value & 0x8000) >> 15;
  72191. var e = (value & 0x7C00) >> 10;
  72192. var f = value & 0x03FF;
  72193. if (e === 0) {
  72194. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72195. }
  72196. else if (e == 0x1F) {
  72197. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72198. }
  72199. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72200. };
  72201. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72202. var destArray = new Float32Array(dataLength);
  72203. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72204. var index = 0;
  72205. for (var y = 0; y < height; y++) {
  72206. for (var x = 0; x < width; x++) {
  72207. var srcPos = (x + y * width) * 4;
  72208. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72209. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72210. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72211. if (DDSTools.StoreLODInAlphaChannel) {
  72212. destArray[index + 3] = lod;
  72213. }
  72214. else {
  72215. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72216. }
  72217. index += 4;
  72218. }
  72219. }
  72220. return destArray;
  72221. };
  72222. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72223. if (DDSTools.StoreLODInAlphaChannel) {
  72224. var destArray = new Uint16Array(dataLength);
  72225. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72226. var index = 0;
  72227. for (var y = 0; y < height; y++) {
  72228. for (var x = 0; x < width; x++) {
  72229. var srcPos = (x + y * width) * 4;
  72230. destArray[index] = srcData[srcPos];
  72231. destArray[index + 1] = srcData[srcPos + 1];
  72232. destArray[index + 2] = srcData[srcPos + 2];
  72233. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72234. index += 4;
  72235. }
  72236. }
  72237. return destArray;
  72238. }
  72239. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72240. };
  72241. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72242. if (DDSTools.StoreLODInAlphaChannel) {
  72243. var destArray = new Float32Array(dataLength);
  72244. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72245. var index = 0;
  72246. for (var y = 0; y < height; y++) {
  72247. for (var x = 0; x < width; x++) {
  72248. var srcPos = (x + y * width) * 4;
  72249. destArray[index] = srcData[srcPos];
  72250. destArray[index + 1] = srcData[srcPos + 1];
  72251. destArray[index + 2] = srcData[srcPos + 2];
  72252. destArray[index + 3] = lod;
  72253. index += 4;
  72254. }
  72255. }
  72256. return destArray;
  72257. }
  72258. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72259. };
  72260. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72261. var destArray = new Uint8Array(dataLength);
  72262. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72263. var index = 0;
  72264. for (var y = 0; y < height; y++) {
  72265. for (var x = 0; x < width; x++) {
  72266. var srcPos = (x + y * width) * 4;
  72267. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72268. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72269. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72270. if (DDSTools.StoreLODInAlphaChannel) {
  72271. destArray[index + 3] = lod;
  72272. }
  72273. else {
  72274. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72275. }
  72276. index += 4;
  72277. }
  72278. }
  72279. return destArray;
  72280. };
  72281. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72282. var destArray = new Uint8Array(dataLength);
  72283. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72284. var index = 0;
  72285. for (var y = 0; y < height; y++) {
  72286. for (var x = 0; x < width; x++) {
  72287. var srcPos = (x + y * width) * 4;
  72288. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72289. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72290. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72291. if (DDSTools.StoreLODInAlphaChannel) {
  72292. destArray[index + 3] = lod;
  72293. }
  72294. else {
  72295. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72296. }
  72297. index += 4;
  72298. }
  72299. }
  72300. return destArray;
  72301. };
  72302. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72303. var byteArray = new Uint8Array(dataLength);
  72304. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72305. var index = 0;
  72306. for (var y = 0; y < height; y++) {
  72307. for (var x = 0; x < width; x++) {
  72308. var srcPos = (x + y * width) * 4;
  72309. byteArray[index] = srcData[srcPos + rOffset];
  72310. byteArray[index + 1] = srcData[srcPos + gOffset];
  72311. byteArray[index + 2] = srcData[srcPos + bOffset];
  72312. byteArray[index + 3] = srcData[srcPos + aOffset];
  72313. index += 4;
  72314. }
  72315. }
  72316. return byteArray;
  72317. };
  72318. DDSTools._ExtractLongWordOrder = function (value) {
  72319. if (value === 255 || value === -16777216) {
  72320. return 0;
  72321. }
  72322. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72323. };
  72324. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72325. var byteArray = new Uint8Array(dataLength);
  72326. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72327. var index = 0;
  72328. for (var y = 0; y < height; y++) {
  72329. for (var x = 0; x < width; x++) {
  72330. var srcPos = (x + y * width) * 3;
  72331. byteArray[index] = srcData[srcPos + rOffset];
  72332. byteArray[index + 1] = srcData[srcPos + gOffset];
  72333. byteArray[index + 2] = srcData[srcPos + bOffset];
  72334. index += 3;
  72335. }
  72336. }
  72337. return byteArray;
  72338. };
  72339. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72340. var byteArray = new Uint8Array(dataLength);
  72341. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72342. var index = 0;
  72343. for (var y = 0; y < height; y++) {
  72344. for (var x = 0; x < width; x++) {
  72345. var srcPos = (x + y * width);
  72346. byteArray[index] = srcData[srcPos];
  72347. index++;
  72348. }
  72349. }
  72350. return byteArray;
  72351. };
  72352. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72353. if (lodIndex === void 0) { lodIndex = -1; }
  72354. var ext = engine.getCaps().s3tc;
  72355. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72356. var fourCC, width, height, dataLength = 0, dataOffset;
  72357. var byteArray, mipmapCount, mip;
  72358. var internalFormat = 0;
  72359. var format = 0;
  72360. var blockBytes = 1;
  72361. if (header[off_magic] !== DDS_MAGIC) {
  72362. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72363. return;
  72364. }
  72365. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72366. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72367. return;
  72368. }
  72369. if (info.isCompressed && !ext) {
  72370. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72371. return;
  72372. }
  72373. var bpp = header[off_RGBbpp];
  72374. dataOffset = header[off_size] + 4;
  72375. var computeFormats = false;
  72376. if (info.isFourCC) {
  72377. fourCC = header[off_pfFourCC];
  72378. switch (fourCC) {
  72379. case FOURCC_DXT1:
  72380. blockBytes = 8;
  72381. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72382. break;
  72383. case FOURCC_DXT3:
  72384. blockBytes = 16;
  72385. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72386. break;
  72387. case FOURCC_DXT5:
  72388. blockBytes = 16;
  72389. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72390. break;
  72391. case FOURCC_D3DFMT_R16G16B16A16F:
  72392. computeFormats = true;
  72393. break;
  72394. case FOURCC_D3DFMT_R32G32B32A32F:
  72395. computeFormats = true;
  72396. break;
  72397. case FOURCC_DX10:
  72398. // There is an additionnal header so dataOffset need to be changed
  72399. dataOffset += 5 * 4; // 5 uints
  72400. var supported = false;
  72401. switch (info.dxgiFormat) {
  72402. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72403. computeFormats = true;
  72404. supported = true;
  72405. break;
  72406. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72407. info.isRGB = true;
  72408. info.isFourCC = false;
  72409. bpp = 32;
  72410. supported = true;
  72411. break;
  72412. }
  72413. if (supported) {
  72414. break;
  72415. }
  72416. default:
  72417. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72418. return;
  72419. }
  72420. }
  72421. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72422. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72423. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72424. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72425. if (computeFormats) {
  72426. format = engine._getWebGLTextureType(info.textureType);
  72427. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72428. }
  72429. mipmapCount = 1;
  72430. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72431. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72432. }
  72433. for (var face = 0; face < faces; face++) {
  72434. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72435. width = header[off_width];
  72436. height = header[off_height];
  72437. for (mip = 0; mip < mipmapCount; ++mip) {
  72438. if (lodIndex === -1 || lodIndex === mip) {
  72439. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72440. var i = (lodIndex === -1) ? mip : 0;
  72441. if (!info.isCompressed && info.isFourCC) {
  72442. dataLength = width * height * 4;
  72443. var floatArray = null;
  72444. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72445. if (bpp === 128) {
  72446. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72447. }
  72448. else if (bpp === 64) {
  72449. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72450. }
  72451. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72452. format = engine._getWebGLTextureType(info.textureType);
  72453. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72454. }
  72455. else {
  72456. if (bpp === 128) {
  72457. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72458. }
  72459. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72460. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72461. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72462. format = engine._getWebGLTextureType(info.textureType);
  72463. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72464. }
  72465. else {
  72466. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72467. }
  72468. }
  72469. if (floatArray) {
  72470. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  72471. }
  72472. }
  72473. else if (info.isRGB) {
  72474. if (bpp === 24) {
  72475. dataLength = width * height * 3;
  72476. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  72477. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  72478. }
  72479. else {
  72480. dataLength = width * height * 4;
  72481. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  72482. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  72483. }
  72484. }
  72485. else if (info.isLuminance) {
  72486. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  72487. var unpaddedRowSize = width;
  72488. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  72489. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  72490. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  72491. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  72492. }
  72493. else {
  72494. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  72495. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  72496. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  72497. }
  72498. }
  72499. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  72500. width *= 0.5;
  72501. height *= 0.5;
  72502. width = Math.max(1.0, width);
  72503. height = Math.max(1.0, height);
  72504. }
  72505. if (currentFace !== undefined) {
  72506. // Loading a single face
  72507. break;
  72508. }
  72509. }
  72510. };
  72511. DDSTools.StoreLODInAlphaChannel = false;
  72512. return DDSTools;
  72513. }());
  72514. BABYLON.DDSTools = DDSTools;
  72515. })(BABYLON || (BABYLON = {}));
  72516. //# sourceMappingURL=babylon.dds.js.map
  72517. var BABYLON;
  72518. (function (BABYLON) {
  72519. /**
  72520. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  72521. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  72522. */
  72523. var KhronosTextureContainer = /** @class */ (function () {
  72524. /**
  72525. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  72526. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  72527. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  72528. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  72529. */
  72530. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  72531. this.arrayBuffer = arrayBuffer;
  72532. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  72533. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  72534. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  72535. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  72536. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  72537. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  72538. BABYLON.Tools.Error("texture missing KTX identifier");
  72539. return;
  72540. }
  72541. // load the reset of the header in native 32 bit int
  72542. var header = new Int32Array(this.arrayBuffer, 12, 13);
  72543. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  72544. var oppositeEndianess = header[0] === 0x01020304;
  72545. // read all the header elements in order they exist in the file, without modification (sans endainness)
  72546. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  72547. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  72548. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  72549. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  72550. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  72551. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  72552. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  72553. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  72554. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  72555. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  72556. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  72557. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  72558. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  72559. if (this.glType !== 0) {
  72560. BABYLON.Tools.Error("only compressed formats currently supported");
  72561. return;
  72562. }
  72563. else {
  72564. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  72565. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  72566. }
  72567. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  72568. BABYLON.Tools.Error("only 2D textures currently supported");
  72569. return;
  72570. }
  72571. if (this.numberOfArrayElements !== 0) {
  72572. BABYLON.Tools.Error("texture arrays not currently supported");
  72573. return;
  72574. }
  72575. if (this.numberOfFaces !== facesExpected) {
  72576. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  72577. return;
  72578. }
  72579. // we now have a completely validated file, so could use existence of loadType as success
  72580. // would need to make this more elaborate & adjust checks above to support more than one load type
  72581. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  72582. }
  72583. // not as fast hardware based, but will probably never need to use
  72584. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  72585. return ((val & 0xFF) << 24)
  72586. | ((val & 0xFF00) << 8)
  72587. | ((val >> 8) & 0xFF00)
  72588. | ((val >> 24) & 0xFF);
  72589. };
  72590. /**
  72591. * It is assumed that the texture has already been created & is currently bound
  72592. */
  72593. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  72594. switch (this.loadType) {
  72595. case KhronosTextureContainer.COMPRESSED_2D:
  72596. this._upload2DCompressedLevels(gl, loadMipmaps);
  72597. break;
  72598. case KhronosTextureContainer.TEX_2D:
  72599. case KhronosTextureContainer.COMPRESSED_3D:
  72600. case KhronosTextureContainer.TEX_3D:
  72601. }
  72602. };
  72603. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  72604. // initialize width & height for level 1
  72605. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  72606. var width = this.pixelWidth;
  72607. var height = this.pixelHeight;
  72608. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  72609. for (var level = 0; level < mipmapCount; level++) {
  72610. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  72611. for (var face = 0; face < this.numberOfFaces; face++) {
  72612. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  72613. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  72614. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  72615. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  72616. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  72617. }
  72618. width = Math.max(1.0, width * 0.5);
  72619. height = Math.max(1.0, height * 0.5);
  72620. }
  72621. };
  72622. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  72623. // load types
  72624. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  72625. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  72626. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  72627. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  72628. return KhronosTextureContainer;
  72629. }());
  72630. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  72631. })(BABYLON || (BABYLON = {}));
  72632. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  72633. var BABYLON;
  72634. (function (BABYLON) {
  72635. var Debug = /** @class */ (function () {
  72636. function Debug() {
  72637. }
  72638. Debug.AxesViewer = /** @class */ (function () {
  72639. function AxesViewer(scene, scaleLines) {
  72640. if (scaleLines === void 0) { scaleLines = 1; }
  72641. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72642. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72643. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72644. this.scaleLines = 1;
  72645. this.scaleLines = scaleLines;
  72646. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  72647. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  72648. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  72649. this._xmesh.renderingGroupId = 2;
  72650. this._ymesh.renderingGroupId = 2;
  72651. this._zmesh.renderingGroupId = 2;
  72652. this._xmesh.material.checkReadyOnlyOnce = true;
  72653. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  72654. this._ymesh.material.checkReadyOnlyOnce = true;
  72655. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  72656. this._zmesh.material.checkReadyOnlyOnce = true;
  72657. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  72658. this.scene = scene;
  72659. }
  72660. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  72661. var scaleLines = this.scaleLines;
  72662. if (this._xmesh) {
  72663. this._xmesh.position.copyFrom(position);
  72664. }
  72665. if (this._ymesh) {
  72666. this._ymesh.position.copyFrom(position);
  72667. }
  72668. if (this._zmesh) {
  72669. this._zmesh.position.copyFrom(position);
  72670. }
  72671. var point2 = this._xline[1];
  72672. point2.x = xaxis.x * scaleLines;
  72673. point2.y = xaxis.y * scaleLines;
  72674. point2.z = xaxis.z * scaleLines;
  72675. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  72676. point2 = this._yline[1];
  72677. point2.x = yaxis.x * scaleLines;
  72678. point2.y = yaxis.y * scaleLines;
  72679. point2.z = yaxis.z * scaleLines;
  72680. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  72681. point2 = this._zline[1];
  72682. point2.x = zaxis.x * scaleLines;
  72683. point2.y = zaxis.y * scaleLines;
  72684. point2.z = zaxis.z * scaleLines;
  72685. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  72686. };
  72687. AxesViewer.prototype.dispose = function () {
  72688. if (this._xmesh) {
  72689. this._xmesh.dispose();
  72690. }
  72691. if (this._ymesh) {
  72692. this._ymesh.dispose();
  72693. }
  72694. if (this._zmesh) {
  72695. this._zmesh.dispose();
  72696. }
  72697. this._xmesh = null;
  72698. this._ymesh = null;
  72699. this._zmesh = null;
  72700. this.scene = null;
  72701. };
  72702. return AxesViewer;
  72703. }());
  72704. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  72705. __extends(BoneAxesViewer, _super);
  72706. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  72707. if (scaleLines === void 0) { scaleLines = 1; }
  72708. var _this = _super.call(this, scene, scaleLines) || this;
  72709. _this.pos = BABYLON.Vector3.Zero();
  72710. _this.xaxis = BABYLON.Vector3.Zero();
  72711. _this.yaxis = BABYLON.Vector3.Zero();
  72712. _this.zaxis = BABYLON.Vector3.Zero();
  72713. _this.mesh = mesh;
  72714. _this.bone = bone;
  72715. return _this;
  72716. }
  72717. BoneAxesViewer.prototype.update = function () {
  72718. if (!this.mesh || !this.bone) {
  72719. return;
  72720. }
  72721. var bone = this.bone;
  72722. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  72723. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  72724. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  72725. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  72726. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  72727. };
  72728. BoneAxesViewer.prototype.dispose = function () {
  72729. if (this.mesh) {
  72730. this.mesh = null;
  72731. this.bone = null;
  72732. _super.prototype.dispose.call(this);
  72733. }
  72734. };
  72735. return BoneAxesViewer;
  72736. }(Debug.AxesViewer));
  72737. Debug.PhysicsViewer = /** @class */ (function () {
  72738. function PhysicsViewer(scene) {
  72739. this._impostors = [];
  72740. this._meshes = [];
  72741. this._numMeshes = 0;
  72742. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72743. var physicEngine = this._scene.getPhysicsEngine();
  72744. if (physicEngine) {
  72745. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  72746. }
  72747. }
  72748. PhysicsViewer.prototype._updateDebugMeshes = function () {
  72749. var plugin = this._physicsEnginePlugin;
  72750. for (var i = 0; i < this._numMeshes; i++) {
  72751. var impostor = this._impostors[i];
  72752. if (!impostor) {
  72753. continue;
  72754. }
  72755. if (impostor.isDisposed) {
  72756. this.hideImpostor(this._impostors[i--]);
  72757. }
  72758. else {
  72759. var mesh = this._meshes[i];
  72760. if (mesh && plugin) {
  72761. plugin.syncMeshWithImpostor(mesh, impostor);
  72762. }
  72763. }
  72764. }
  72765. };
  72766. PhysicsViewer.prototype.showImpostor = function (impostor) {
  72767. if (!this._scene) {
  72768. return;
  72769. }
  72770. for (var i = 0; i < this._numMeshes; i++) {
  72771. if (this._impostors[i] == impostor) {
  72772. return;
  72773. }
  72774. }
  72775. var debugMesh = this._getDebugMesh(impostor, this._scene);
  72776. if (debugMesh) {
  72777. this._impostors[this._numMeshes] = impostor;
  72778. this._meshes[this._numMeshes] = debugMesh;
  72779. if (this._numMeshes === 0) {
  72780. this._renderFunction = this._updateDebugMeshes.bind(this);
  72781. this._scene.registerBeforeRender(this._renderFunction);
  72782. }
  72783. this._numMeshes++;
  72784. }
  72785. };
  72786. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  72787. if (!impostor || !this._scene) {
  72788. return;
  72789. }
  72790. var removed = false;
  72791. for (var i = 0; i < this._numMeshes; i++) {
  72792. if (this._impostors[i] == impostor) {
  72793. var mesh = this._meshes[i];
  72794. if (!mesh) {
  72795. continue;
  72796. }
  72797. this._scene.removeMesh(mesh);
  72798. mesh.dispose();
  72799. this._numMeshes--;
  72800. if (this._numMeshes > 0) {
  72801. this._meshes[i] = this._meshes[this._numMeshes];
  72802. this._impostors[i] = this._impostors[this._numMeshes];
  72803. this._meshes[this._numMeshes] = null;
  72804. this._impostors[this._numMeshes] = null;
  72805. }
  72806. else {
  72807. this._meshes[0] = null;
  72808. this._impostors[0] = null;
  72809. }
  72810. removed = true;
  72811. break;
  72812. }
  72813. }
  72814. if (removed && this._numMeshes === 0) {
  72815. this._scene.unregisterBeforeRender(this._renderFunction);
  72816. }
  72817. };
  72818. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  72819. if (!this._debugMaterial) {
  72820. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  72821. this._debugMaterial.wireframe = true;
  72822. }
  72823. return this._debugMaterial;
  72824. };
  72825. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  72826. if (!this._debugBoxMesh) {
  72827. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  72828. this._debugBoxMesh.renderingGroupId = 1;
  72829. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72830. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  72831. scene.removeMesh(this._debugBoxMesh);
  72832. }
  72833. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  72834. };
  72835. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  72836. if (!this._debugSphereMesh) {
  72837. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  72838. this._debugSphereMesh.renderingGroupId = 1;
  72839. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72840. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  72841. scene.removeMesh(this._debugSphereMesh);
  72842. }
  72843. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  72844. };
  72845. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  72846. var mesh = null;
  72847. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  72848. mesh = this._getDebugBoxMesh(scene);
  72849. impostor.getBoxSizeToRef(mesh.scaling);
  72850. }
  72851. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  72852. mesh = this._getDebugSphereMesh(scene);
  72853. var radius = impostor.getRadius();
  72854. mesh.scaling.x = radius * 2;
  72855. mesh.scaling.y = radius * 2;
  72856. mesh.scaling.z = radius * 2;
  72857. }
  72858. return mesh;
  72859. };
  72860. PhysicsViewer.prototype.dispose = function () {
  72861. for (var i = 0; i < this._numMeshes; i++) {
  72862. this.hideImpostor(this._impostors[i]);
  72863. }
  72864. if (this._debugBoxMesh) {
  72865. this._debugBoxMesh.dispose();
  72866. }
  72867. if (this._debugSphereMesh) {
  72868. this._debugSphereMesh.dispose();
  72869. }
  72870. if (this._debugMaterial) {
  72871. this._debugMaterial.dispose();
  72872. }
  72873. this._impostors.length = 0;
  72874. this._scene = null;
  72875. this._physicsEnginePlugin = null;
  72876. };
  72877. return PhysicsViewer;
  72878. }());
  72879. Debug.SkeletonViewer = /** @class */ (function () {
  72880. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  72881. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  72882. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  72883. this.skeleton = skeleton;
  72884. this.mesh = mesh;
  72885. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  72886. this.renderingGroupId = renderingGroupId;
  72887. this.color = BABYLON.Color3.White();
  72888. this._debugLines = new Array();
  72889. this._isEnabled = false;
  72890. this._scene = scene;
  72891. this.update();
  72892. this._renderFunction = this.update.bind(this);
  72893. }
  72894. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  72895. get: function () {
  72896. return this._isEnabled;
  72897. },
  72898. set: function (value) {
  72899. if (this._isEnabled === value) {
  72900. return;
  72901. }
  72902. this._isEnabled = value;
  72903. if (value) {
  72904. this._scene.registerBeforeRender(this._renderFunction);
  72905. }
  72906. else {
  72907. this._scene.unregisterBeforeRender(this._renderFunction);
  72908. }
  72909. },
  72910. enumerable: true,
  72911. configurable: true
  72912. });
  72913. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  72914. if (x === void 0) { x = 0; }
  72915. if (y === void 0) { y = 0; }
  72916. if (z === void 0) { z = 0; }
  72917. var tmat = BABYLON.Tmp.Matrix[0];
  72918. var parentBone = bone.getParent();
  72919. tmat.copyFrom(bone.getLocalMatrix());
  72920. if (x !== 0 || y !== 0 || z !== 0) {
  72921. var tmat2 = BABYLON.Tmp.Matrix[1];
  72922. BABYLON.Matrix.IdentityToRef(tmat2);
  72923. tmat2.m[12] = x;
  72924. tmat2.m[13] = y;
  72925. tmat2.m[14] = z;
  72926. tmat2.multiplyToRef(tmat, tmat);
  72927. }
  72928. if (parentBone) {
  72929. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  72930. }
  72931. tmat.multiplyToRef(meshMat, tmat);
  72932. position.x = tmat.m[12];
  72933. position.y = tmat.m[13];
  72934. position.z = tmat.m[14];
  72935. };
  72936. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  72937. var len = bones.length;
  72938. var meshPos = this.mesh.position;
  72939. for (var i = 0; i < len; i++) {
  72940. var bone = bones[i];
  72941. var points = this._debugLines[i];
  72942. if (!points) {
  72943. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72944. this._debugLines[i] = points;
  72945. }
  72946. this._getBonePosition(points[0], bone, meshMat);
  72947. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  72948. points[0].subtractInPlace(meshPos);
  72949. points[1].subtractInPlace(meshPos);
  72950. }
  72951. };
  72952. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  72953. var len = bones.length;
  72954. var boneNum = 0;
  72955. var meshPos = this.mesh.position;
  72956. for (var i = len - 1; i >= 0; i--) {
  72957. var childBone = bones[i];
  72958. var parentBone = childBone.getParent();
  72959. if (!parentBone) {
  72960. continue;
  72961. }
  72962. var points = this._debugLines[boneNum];
  72963. if (!points) {
  72964. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72965. this._debugLines[boneNum] = points;
  72966. }
  72967. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  72968. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  72969. points[0].subtractInPlace(meshPos);
  72970. points[1].subtractInPlace(meshPos);
  72971. boneNum++;
  72972. }
  72973. };
  72974. SkeletonViewer.prototype.update = function () {
  72975. if (this.autoUpdateBonesMatrices) {
  72976. this.skeleton.computeAbsoluteTransforms();
  72977. }
  72978. if (this.skeleton.bones[0].length === undefined) {
  72979. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  72980. }
  72981. else {
  72982. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  72983. }
  72984. if (!this._debugMesh) {
  72985. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  72986. this._debugMesh.renderingGroupId = this.renderingGroupId;
  72987. }
  72988. else {
  72989. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  72990. }
  72991. this._debugMesh.position.copyFrom(this.mesh.position);
  72992. this._debugMesh.color = this.color;
  72993. };
  72994. SkeletonViewer.prototype.dispose = function () {
  72995. if (this._debugMesh) {
  72996. this.isEnabled = false;
  72997. this._debugMesh.dispose();
  72998. this._debugMesh = null;
  72999. }
  73000. };
  73001. return SkeletonViewer;
  73002. }());
  73003. return Debug;
  73004. }());
  73005. BABYLON.Debug = Debug;
  73006. })(BABYLON || (BABYLON = {}));
  73007. //# sourceMappingURL=babylon.debugModules.js.map
  73008. var BABYLON;
  73009. (function (BABYLON) {
  73010. var RayHelper = /** @class */ (function () {
  73011. function RayHelper(ray) {
  73012. this.ray = ray;
  73013. }
  73014. RayHelper.CreateAndShow = function (ray, scene, color) {
  73015. var helper = new RayHelper(ray);
  73016. helper.show(scene, color);
  73017. return helper;
  73018. };
  73019. RayHelper.prototype.show = function (scene, color) {
  73020. if (!this._renderFunction && this.ray) {
  73021. var ray = this.ray;
  73022. this._renderFunction = this._render.bind(this);
  73023. this._scene = scene;
  73024. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73025. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73026. if (this._renderFunction) {
  73027. this._scene.registerBeforeRender(this._renderFunction);
  73028. }
  73029. }
  73030. if (color && this._renderLine) {
  73031. this._renderLine.color.copyFrom(color);
  73032. }
  73033. };
  73034. RayHelper.prototype.hide = function () {
  73035. if (this._renderFunction && this._scene) {
  73036. this._scene.unregisterBeforeRender(this._renderFunction);
  73037. this._scene = null;
  73038. this._renderFunction = null;
  73039. if (this._renderLine) {
  73040. this._renderLine.dispose();
  73041. this._renderLine = null;
  73042. }
  73043. this._renderPoints = [];
  73044. }
  73045. };
  73046. RayHelper.prototype._render = function () {
  73047. var ray = this.ray;
  73048. if (!ray) {
  73049. return;
  73050. }
  73051. var point = this._renderPoints[1];
  73052. var len = Math.min(ray.length, 1000000);
  73053. point.copyFrom(ray.direction);
  73054. point.scaleInPlace(len);
  73055. point.addInPlace(ray.origin);
  73056. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73057. };
  73058. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73059. this._attachedToMesh = mesh;
  73060. var ray = this.ray;
  73061. if (!ray) {
  73062. return;
  73063. }
  73064. if (!ray.direction) {
  73065. ray.direction = BABYLON.Vector3.Zero();
  73066. }
  73067. if (!ray.origin) {
  73068. ray.origin = BABYLON.Vector3.Zero();
  73069. }
  73070. if (length) {
  73071. ray.length = length;
  73072. }
  73073. if (!meshSpaceOrigin) {
  73074. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73075. }
  73076. if (!meshSpaceDirection) {
  73077. // -1 so that this will work with Mesh.lookAt
  73078. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73079. }
  73080. if (!this._meshSpaceDirection) {
  73081. this._meshSpaceDirection = meshSpaceDirection.clone();
  73082. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73083. }
  73084. else {
  73085. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73086. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73087. }
  73088. if (!this._updateToMeshFunction) {
  73089. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73090. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73091. }
  73092. this._updateToMesh();
  73093. };
  73094. RayHelper.prototype.detachFromMesh = function () {
  73095. if (this._attachedToMesh) {
  73096. if (this._updateToMeshFunction) {
  73097. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73098. }
  73099. this._attachedToMesh = null;
  73100. this._updateToMeshFunction = null;
  73101. }
  73102. };
  73103. RayHelper.prototype._updateToMesh = function () {
  73104. var ray = this.ray;
  73105. if (!this._attachedToMesh || !ray) {
  73106. return;
  73107. }
  73108. if (this._attachedToMesh._isDisposed) {
  73109. this.detachFromMesh();
  73110. return;
  73111. }
  73112. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73113. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73114. };
  73115. RayHelper.prototype.dispose = function () {
  73116. this.hide();
  73117. this.detachFromMesh();
  73118. this.ray = null;
  73119. };
  73120. return RayHelper;
  73121. }());
  73122. BABYLON.RayHelper = RayHelper;
  73123. })(BABYLON || (BABYLON = {}));
  73124. //# sourceMappingURL=babylon.rayHelper.js.map
  73125. var BABYLON;
  73126. (function (BABYLON) {
  73127. // load the inspector using require, if not present in the global namespace.
  73128. var DebugLayer = /** @class */ (function () {
  73129. function DebugLayer(scene) {
  73130. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73131. this._scene = scene;
  73132. // load inspector using require, if it doesn't exist on the global namespace.
  73133. }
  73134. /** Creates the inspector window. */
  73135. DebugLayer.prototype._createInspector = function (config) {
  73136. if (config === void 0) { config = {}; }
  73137. var popup = config.popup || false;
  73138. var initialTab = config.initialTab || 0;
  73139. var parentElement = config.parentElement || null;
  73140. if (!this._inspector) {
  73141. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73142. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73143. } // else nothing to do,; instance is already existing
  73144. };
  73145. DebugLayer.prototype.isVisible = function () {
  73146. if (!this._inspector) {
  73147. return false;
  73148. }
  73149. return true;
  73150. };
  73151. DebugLayer.prototype.hide = function () {
  73152. if (this._inspector) {
  73153. try {
  73154. this._inspector.dispose();
  73155. }
  73156. catch (e) {
  73157. // If the inspector has been removed directly from the inspector tool
  73158. }
  73159. this._inspector = null;
  73160. }
  73161. };
  73162. DebugLayer.prototype.show = function (config) {
  73163. if (config === void 0) { config = {}; }
  73164. if (typeof this.BJSINSPECTOR == 'undefined') {
  73165. // Load inspector and add it to the DOM
  73166. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73167. }
  73168. else {
  73169. // Otherwise creates the inspector
  73170. this._createInspector(config);
  73171. }
  73172. };
  73173. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73174. return DebugLayer;
  73175. }());
  73176. BABYLON.DebugLayer = DebugLayer;
  73177. })(BABYLON || (BABYLON = {}));
  73178. //# sourceMappingURL=babylon.debugLayer.js.map
  73179. var BABYLON;
  73180. (function (BABYLON) {
  73181. var BoundingBoxRenderer = /** @class */ (function () {
  73182. function BoundingBoxRenderer(scene) {
  73183. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73184. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73185. this.showBackLines = true;
  73186. this.renderList = new BABYLON.SmartArray(32);
  73187. this._vertexBuffers = {};
  73188. this._scene = scene;
  73189. }
  73190. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73191. if (this._colorShader) {
  73192. return;
  73193. }
  73194. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73195. attributes: [BABYLON.VertexBuffer.PositionKind],
  73196. uniforms: ["world", "viewProjection", "color"]
  73197. });
  73198. var engine = this._scene.getEngine();
  73199. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73201. this._createIndexBuffer();
  73202. };
  73203. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73204. var engine = this._scene.getEngine();
  73205. 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]);
  73206. };
  73207. BoundingBoxRenderer.prototype._rebuild = function () {
  73208. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73209. if (vb) {
  73210. vb._rebuild();
  73211. }
  73212. this._createIndexBuffer();
  73213. };
  73214. BoundingBoxRenderer.prototype.reset = function () {
  73215. this.renderList.reset();
  73216. };
  73217. BoundingBoxRenderer.prototype.render = function () {
  73218. if (this.renderList.length === 0) {
  73219. return;
  73220. }
  73221. this._prepareRessources();
  73222. if (!this._colorShader.isReady()) {
  73223. return;
  73224. }
  73225. var engine = this._scene.getEngine();
  73226. engine.setDepthWrite(false);
  73227. this._colorShader._preBind();
  73228. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73229. var boundingBox = this.renderList.data[boundingBoxIndex];
  73230. var min = boundingBox.minimum;
  73231. var max = boundingBox.maximum;
  73232. var diff = max.subtract(min);
  73233. var median = min.add(diff.scale(0.5));
  73234. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73235. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73236. .multiply(boundingBox.getWorldMatrix());
  73237. // VBOs
  73238. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73239. if (this.showBackLines) {
  73240. // Back
  73241. engine.setDepthFunctionToGreaterOrEqual();
  73242. this._scene.resetCachedMaterial();
  73243. this._colorShader.setColor4("color", this.backColor.toColor4());
  73244. this._colorShader.bind(worldMatrix);
  73245. // Draw order
  73246. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73247. }
  73248. // Front
  73249. engine.setDepthFunctionToLess();
  73250. this._scene.resetCachedMaterial();
  73251. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73252. this._colorShader.bind(worldMatrix);
  73253. // Draw order
  73254. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73255. }
  73256. this._colorShader.unbind();
  73257. engine.setDepthFunctionToLessOrEqual();
  73258. engine.setDepthWrite(true);
  73259. };
  73260. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73261. this._prepareRessources();
  73262. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73263. return;
  73264. }
  73265. var engine = this._scene.getEngine();
  73266. engine.setDepthWrite(false);
  73267. engine.setColorWrite(false);
  73268. this._colorShader._preBind();
  73269. var boundingBox = mesh._boundingInfo.boundingBox;
  73270. var min = boundingBox.minimum;
  73271. var max = boundingBox.maximum;
  73272. var diff = max.subtract(min);
  73273. var median = min.add(diff.scale(0.5));
  73274. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73275. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73276. .multiply(boundingBox.getWorldMatrix());
  73277. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73278. engine.setDepthFunctionToLess();
  73279. this._scene.resetCachedMaterial();
  73280. this._colorShader.bind(worldMatrix);
  73281. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73282. this._colorShader.unbind();
  73283. engine.setDepthFunctionToLessOrEqual();
  73284. engine.setDepthWrite(true);
  73285. engine.setColorWrite(true);
  73286. };
  73287. BoundingBoxRenderer.prototype.dispose = function () {
  73288. if (!this._colorShader) {
  73289. return;
  73290. }
  73291. this.renderList.dispose();
  73292. this._colorShader.dispose();
  73293. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73294. if (buffer) {
  73295. buffer.dispose();
  73296. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73297. }
  73298. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73299. };
  73300. return BoundingBoxRenderer;
  73301. }());
  73302. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73303. })(BABYLON || (BABYLON = {}));
  73304. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73305. var BABYLON;
  73306. (function (BABYLON) {
  73307. var MorphTarget = /** @class */ (function () {
  73308. function MorphTarget(name, influence) {
  73309. if (influence === void 0) { influence = 0; }
  73310. this.name = name;
  73311. this.animations = new Array();
  73312. this._positions = null;
  73313. this._normals = null;
  73314. this._tangents = null;
  73315. this.onInfluenceChanged = new BABYLON.Observable();
  73316. this.influence = influence;
  73317. }
  73318. Object.defineProperty(MorphTarget.prototype, "influence", {
  73319. get: function () {
  73320. return this._influence;
  73321. },
  73322. set: function (influence) {
  73323. if (this._influence === influence) {
  73324. return;
  73325. }
  73326. var previous = this._influence;
  73327. this._influence = influence;
  73328. if (this.onInfluenceChanged.hasObservers) {
  73329. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73330. }
  73331. },
  73332. enumerable: true,
  73333. configurable: true
  73334. });
  73335. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73336. get: function () {
  73337. return !!this._positions;
  73338. },
  73339. enumerable: true,
  73340. configurable: true
  73341. });
  73342. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73343. get: function () {
  73344. return !!this._normals;
  73345. },
  73346. enumerable: true,
  73347. configurable: true
  73348. });
  73349. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73350. get: function () {
  73351. return !!this._tangents;
  73352. },
  73353. enumerable: true,
  73354. configurable: true
  73355. });
  73356. MorphTarget.prototype.setPositions = function (data) {
  73357. this._positions = data;
  73358. };
  73359. MorphTarget.prototype.getPositions = function () {
  73360. return this._positions;
  73361. };
  73362. MorphTarget.prototype.setNormals = function (data) {
  73363. this._normals = data;
  73364. };
  73365. MorphTarget.prototype.getNormals = function () {
  73366. return this._normals;
  73367. };
  73368. MorphTarget.prototype.setTangents = function (data) {
  73369. this._tangents = data;
  73370. };
  73371. MorphTarget.prototype.getTangents = function () {
  73372. return this._tangents;
  73373. };
  73374. /**
  73375. * Serializes the current target into a Serialization object.
  73376. * Returns the serialized object.
  73377. */
  73378. MorphTarget.prototype.serialize = function () {
  73379. var serializationObject = {};
  73380. serializationObject.name = this.name;
  73381. serializationObject.influence = this.influence;
  73382. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73383. if (this.hasNormals) {
  73384. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73385. }
  73386. if (this.hasTangents) {
  73387. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73388. }
  73389. // Animations
  73390. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73391. return serializationObject;
  73392. };
  73393. // Statics
  73394. MorphTarget.Parse = function (serializationObject) {
  73395. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73396. result.setPositions(serializationObject.positions);
  73397. if (serializationObject.normals) {
  73398. result.setNormals(serializationObject.normals);
  73399. }
  73400. if (serializationObject.tangents) {
  73401. result.setTangents(serializationObject.tangents);
  73402. }
  73403. // Animations
  73404. if (serializationObject.animations) {
  73405. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73406. var parsedAnimation = serializationObject.animations[animationIndex];
  73407. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73408. }
  73409. }
  73410. return result;
  73411. };
  73412. MorphTarget.FromMesh = function (mesh, name, influence) {
  73413. if (!name) {
  73414. name = mesh.name;
  73415. }
  73416. var result = new MorphTarget(name, influence);
  73417. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73418. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73419. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73420. }
  73421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73422. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73423. }
  73424. return result;
  73425. };
  73426. return MorphTarget;
  73427. }());
  73428. BABYLON.MorphTarget = MorphTarget;
  73429. })(BABYLON || (BABYLON = {}));
  73430. //# sourceMappingURL=babylon.morphTarget.js.map
  73431. var BABYLON;
  73432. (function (BABYLON) {
  73433. var MorphTargetManager = /** @class */ (function () {
  73434. function MorphTargetManager(scene) {
  73435. if (scene === void 0) { scene = null; }
  73436. this._targets = new Array();
  73437. this._targetObservable = new Array();
  73438. this._activeTargets = new BABYLON.SmartArray(16);
  73439. this._supportsNormals = false;
  73440. this._supportsTangents = false;
  73441. this._vertexCount = 0;
  73442. this._uniqueId = 0;
  73443. this._tempInfluences = new Array();
  73444. if (!scene) {
  73445. scene = BABYLON.Engine.LastCreatedScene;
  73446. }
  73447. this._scene = scene;
  73448. if (this._scene) {
  73449. this._scene.morphTargetManagers.push(this);
  73450. this._uniqueId = this._scene.getUniqueId();
  73451. }
  73452. }
  73453. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73454. get: function () {
  73455. return this._uniqueId;
  73456. },
  73457. enumerable: true,
  73458. configurable: true
  73459. });
  73460. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73461. get: function () {
  73462. return this._vertexCount;
  73463. },
  73464. enumerable: true,
  73465. configurable: true
  73466. });
  73467. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  73468. get: function () {
  73469. return this._supportsNormals;
  73470. },
  73471. enumerable: true,
  73472. configurable: true
  73473. });
  73474. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  73475. get: function () {
  73476. return this._supportsTangents;
  73477. },
  73478. enumerable: true,
  73479. configurable: true
  73480. });
  73481. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  73482. get: function () {
  73483. return this._targets.length;
  73484. },
  73485. enumerable: true,
  73486. configurable: true
  73487. });
  73488. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  73489. get: function () {
  73490. return this._activeTargets.length;
  73491. },
  73492. enumerable: true,
  73493. configurable: true
  73494. });
  73495. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  73496. get: function () {
  73497. return this._influences;
  73498. },
  73499. enumerable: true,
  73500. configurable: true
  73501. });
  73502. MorphTargetManager.prototype.getActiveTarget = function (index) {
  73503. return this._activeTargets.data[index];
  73504. };
  73505. MorphTargetManager.prototype.getTarget = function (index) {
  73506. return this._targets[index];
  73507. };
  73508. MorphTargetManager.prototype.addTarget = function (target) {
  73509. var _this = this;
  73510. this._targets.push(target);
  73511. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  73512. _this._syncActiveTargets(needUpdate);
  73513. }));
  73514. this._syncActiveTargets(true);
  73515. };
  73516. MorphTargetManager.prototype.removeTarget = function (target) {
  73517. var index = this._targets.indexOf(target);
  73518. if (index >= 0) {
  73519. this._targets.splice(index, 1);
  73520. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  73521. this._syncActiveTargets(true);
  73522. }
  73523. };
  73524. /**
  73525. * Serializes the current manager into a Serialization object.
  73526. * Returns the serialized object.
  73527. */
  73528. MorphTargetManager.prototype.serialize = function () {
  73529. var serializationObject = {};
  73530. serializationObject.id = this.uniqueId;
  73531. serializationObject.targets = [];
  73532. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73533. var target = _a[_i];
  73534. serializationObject.targets.push(target.serialize());
  73535. }
  73536. return serializationObject;
  73537. };
  73538. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  73539. var influenceCount = 0;
  73540. this._activeTargets.reset();
  73541. this._supportsNormals = true;
  73542. this._supportsTangents = true;
  73543. this._vertexCount = 0;
  73544. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73545. var target = _a[_i];
  73546. this._activeTargets.push(target);
  73547. this._tempInfluences[influenceCount++] = target.influence;
  73548. var positions = target.getPositions();
  73549. if (positions) {
  73550. this._supportsNormals = this._supportsNormals && target.hasNormals;
  73551. this._supportsTangents = this._supportsTangents && target.hasTangents;
  73552. var vertexCount = positions.length / 3;
  73553. if (this._vertexCount === 0) {
  73554. this._vertexCount = vertexCount;
  73555. }
  73556. else if (this._vertexCount !== vertexCount) {
  73557. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  73558. return;
  73559. }
  73560. }
  73561. }
  73562. if (!this._influences || this._influences.length !== influenceCount) {
  73563. this._influences = new Float32Array(influenceCount);
  73564. }
  73565. for (var index = 0; index < influenceCount; index++) {
  73566. this._influences[index] = this._tempInfluences[index];
  73567. }
  73568. if (needUpdate && this._scene) {
  73569. // Flag meshes as dirty to resync with the active targets
  73570. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  73571. var mesh = _c[_b];
  73572. if (mesh.morphTargetManager === this) {
  73573. mesh._syncGeometryWithMorphTargetManager();
  73574. }
  73575. }
  73576. }
  73577. };
  73578. // Statics
  73579. MorphTargetManager.Parse = function (serializationObject, scene) {
  73580. var result = new MorphTargetManager(scene);
  73581. result._uniqueId = serializationObject.id;
  73582. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  73583. var targetData = _a[_i];
  73584. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  73585. }
  73586. return result;
  73587. };
  73588. return MorphTargetManager;
  73589. }());
  73590. BABYLON.MorphTargetManager = MorphTargetManager;
  73591. })(BABYLON || (BABYLON = {}));
  73592. //# sourceMappingURL=babylon.morphTargetManager.js.map
  73593. var BABYLON;
  73594. (function (BABYLON) {
  73595. var Octree = /** @class */ (function () {
  73596. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  73597. if (maxDepth === void 0) { maxDepth = 2; }
  73598. this.maxDepth = maxDepth;
  73599. this.dynamicContent = new Array();
  73600. this._maxBlockCapacity = maxBlockCapacity || 64;
  73601. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  73602. this._creationFunc = creationFunc;
  73603. }
  73604. // Methods
  73605. Octree.prototype.update = function (worldMin, worldMax, entries) {
  73606. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  73607. };
  73608. Octree.prototype.addMesh = function (entry) {
  73609. for (var index = 0; index < this.blocks.length; index++) {
  73610. var block = this.blocks[index];
  73611. block.addEntry(entry);
  73612. }
  73613. };
  73614. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  73615. this._selectionContent.reset();
  73616. for (var index = 0; index < this.blocks.length; index++) {
  73617. var block = this.blocks[index];
  73618. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  73619. }
  73620. if (allowDuplicate) {
  73621. this._selectionContent.concat(this.dynamicContent);
  73622. }
  73623. else {
  73624. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73625. }
  73626. return this._selectionContent;
  73627. };
  73628. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  73629. this._selectionContent.reset();
  73630. for (var index = 0; index < this.blocks.length; index++) {
  73631. var block = this.blocks[index];
  73632. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  73633. }
  73634. if (allowDuplicate) {
  73635. this._selectionContent.concat(this.dynamicContent);
  73636. }
  73637. else {
  73638. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73639. }
  73640. return this._selectionContent;
  73641. };
  73642. Octree.prototype.intersectsRay = function (ray) {
  73643. this._selectionContent.reset();
  73644. for (var index = 0; index < this.blocks.length; index++) {
  73645. var block = this.blocks[index];
  73646. block.intersectsRay(ray, this._selectionContent);
  73647. }
  73648. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73649. return this._selectionContent;
  73650. };
  73651. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  73652. target.blocks = new Array();
  73653. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  73654. // Segmenting space
  73655. for (var x = 0; x < 2; x++) {
  73656. for (var y = 0; y < 2; y++) {
  73657. for (var z = 0; z < 2; z++) {
  73658. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  73659. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  73660. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  73661. block.addEntries(entries);
  73662. target.blocks.push(block);
  73663. }
  73664. }
  73665. }
  73666. };
  73667. Octree.CreationFuncForMeshes = function (entry, block) {
  73668. var boundingInfo = entry.getBoundingInfo();
  73669. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73670. block.entries.push(entry);
  73671. }
  73672. };
  73673. Octree.CreationFuncForSubMeshes = function (entry, block) {
  73674. var boundingInfo = entry.getBoundingInfo();
  73675. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73676. block.entries.push(entry);
  73677. }
  73678. };
  73679. return Octree;
  73680. }());
  73681. BABYLON.Octree = Octree;
  73682. })(BABYLON || (BABYLON = {}));
  73683. //# sourceMappingURL=babylon.octree.js.map
  73684. var BABYLON;
  73685. (function (BABYLON) {
  73686. var OctreeBlock = /** @class */ (function () {
  73687. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  73688. this.entries = new Array();
  73689. this._boundingVectors = new Array();
  73690. this._capacity = capacity;
  73691. this._depth = depth;
  73692. this._maxDepth = maxDepth;
  73693. this._creationFunc = creationFunc;
  73694. this._minPoint = minPoint;
  73695. this._maxPoint = maxPoint;
  73696. this._boundingVectors.push(minPoint.clone());
  73697. this._boundingVectors.push(maxPoint.clone());
  73698. this._boundingVectors.push(minPoint.clone());
  73699. this._boundingVectors[2].x = maxPoint.x;
  73700. this._boundingVectors.push(minPoint.clone());
  73701. this._boundingVectors[3].y = maxPoint.y;
  73702. this._boundingVectors.push(minPoint.clone());
  73703. this._boundingVectors[4].z = maxPoint.z;
  73704. this._boundingVectors.push(maxPoint.clone());
  73705. this._boundingVectors[5].z = minPoint.z;
  73706. this._boundingVectors.push(maxPoint.clone());
  73707. this._boundingVectors[6].x = minPoint.x;
  73708. this._boundingVectors.push(maxPoint.clone());
  73709. this._boundingVectors[7].y = minPoint.y;
  73710. }
  73711. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  73712. // Property
  73713. get: function () {
  73714. return this._capacity;
  73715. },
  73716. enumerable: true,
  73717. configurable: true
  73718. });
  73719. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  73720. get: function () {
  73721. return this._minPoint;
  73722. },
  73723. enumerable: true,
  73724. configurable: true
  73725. });
  73726. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  73727. get: function () {
  73728. return this._maxPoint;
  73729. },
  73730. enumerable: true,
  73731. configurable: true
  73732. });
  73733. // Methods
  73734. OctreeBlock.prototype.addEntry = function (entry) {
  73735. if (this.blocks) {
  73736. for (var index = 0; index < this.blocks.length; index++) {
  73737. var block = this.blocks[index];
  73738. block.addEntry(entry);
  73739. }
  73740. return;
  73741. }
  73742. this._creationFunc(entry, this);
  73743. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  73744. this.createInnerBlocks();
  73745. }
  73746. };
  73747. OctreeBlock.prototype.addEntries = function (entries) {
  73748. for (var index = 0; index < entries.length; index++) {
  73749. var mesh = entries[index];
  73750. this.addEntry(mesh);
  73751. }
  73752. };
  73753. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  73754. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  73755. if (this.blocks) {
  73756. for (var index = 0; index < this.blocks.length; index++) {
  73757. var block = this.blocks[index];
  73758. block.select(frustumPlanes, selection, allowDuplicate);
  73759. }
  73760. return;
  73761. }
  73762. if (allowDuplicate) {
  73763. selection.concat(this.entries);
  73764. }
  73765. else {
  73766. selection.concatWithNoDuplicate(this.entries);
  73767. }
  73768. }
  73769. };
  73770. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  73771. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  73772. if (this.blocks) {
  73773. for (var index = 0; index < this.blocks.length; index++) {
  73774. var block = this.blocks[index];
  73775. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  73776. }
  73777. return;
  73778. }
  73779. if (allowDuplicate) {
  73780. selection.concat(this.entries);
  73781. }
  73782. else {
  73783. selection.concatWithNoDuplicate(this.entries);
  73784. }
  73785. }
  73786. };
  73787. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  73788. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  73789. if (this.blocks) {
  73790. for (var index = 0; index < this.blocks.length; index++) {
  73791. var block = this.blocks[index];
  73792. block.intersectsRay(ray, selection);
  73793. }
  73794. return;
  73795. }
  73796. selection.concatWithNoDuplicate(this.entries);
  73797. }
  73798. };
  73799. OctreeBlock.prototype.createInnerBlocks = function () {
  73800. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  73801. };
  73802. return OctreeBlock;
  73803. }());
  73804. BABYLON.OctreeBlock = OctreeBlock;
  73805. })(BABYLON || (BABYLON = {}));
  73806. //# sourceMappingURL=babylon.octreeBlock.js.map
  73807. var BABYLON;
  73808. (function (BABYLON) {
  73809. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  73810. __extends(VRDistortionCorrectionPostProcess, _super);
  73811. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  73812. var _this = _super.call(this, name, "vrDistortionCorrection", [
  73813. 'LensCenter',
  73814. 'Scale',
  73815. 'ScaleIn',
  73816. 'HmdWarpParam'
  73817. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  73818. _this._isRightEye = isRightEye;
  73819. _this._distortionFactors = vrMetrics.distortionK;
  73820. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  73821. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  73822. _this.adaptScaleToCurrentViewport = true;
  73823. _this.onSizeChangedObservable.add(function () {
  73824. _this.aspectRatio = _this.width * .5 / _this.height;
  73825. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  73826. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  73827. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  73828. });
  73829. _this.onApplyObservable.add(function (effect) {
  73830. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  73831. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  73832. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  73833. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  73834. });
  73835. return _this;
  73836. }
  73837. return VRDistortionCorrectionPostProcess;
  73838. }(BABYLON.PostProcess));
  73839. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  73840. })(BABYLON || (BABYLON = {}));
  73841. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  73842. var BABYLON;
  73843. (function (BABYLON) {
  73844. var AnaglyphPostProcess = /** @class */ (function (_super) {
  73845. __extends(AnaglyphPostProcess, _super);
  73846. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  73847. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  73848. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73849. _this.onApplyObservable.add(function (effect) {
  73850. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  73851. });
  73852. return _this;
  73853. }
  73854. return AnaglyphPostProcess;
  73855. }(BABYLON.PostProcess));
  73856. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  73857. })(BABYLON || (BABYLON = {}));
  73858. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  73859. var BABYLON;
  73860. (function (BABYLON) {
  73861. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  73862. __extends(StereoscopicInterlacePostProcess, _super);
  73863. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  73864. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  73865. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73866. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73867. _this.onSizeChangedObservable.add(function () {
  73868. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73869. });
  73870. _this.onApplyObservable.add(function (effect) {
  73871. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  73872. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  73873. });
  73874. return _this;
  73875. }
  73876. return StereoscopicInterlacePostProcess;
  73877. }(BABYLON.PostProcess));
  73878. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  73879. })(BABYLON || (BABYLON = {}));
  73880. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  73881. var BABYLON;
  73882. (function (BABYLON) {
  73883. /**
  73884. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  73885. * Screen rotation is taken into account.
  73886. */
  73887. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  73888. function FreeCameraDeviceOrientationInput() {
  73889. var _this = this;
  73890. this._screenOrientationAngle = 0;
  73891. this._screenQuaternion = new BABYLON.Quaternion();
  73892. this._alpha = 0;
  73893. this._beta = 0;
  73894. this._gamma = 0;
  73895. this._orientationChanged = function () {
  73896. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  73897. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  73898. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  73899. };
  73900. this._deviceOrientation = function (evt) {
  73901. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  73902. _this._beta = evt.beta !== null ? evt.beta : 0;
  73903. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  73904. };
  73905. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  73906. this._orientationChanged();
  73907. }
  73908. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  73909. get: function () {
  73910. return this._camera;
  73911. },
  73912. set: function (camera) {
  73913. this._camera = camera;
  73914. if (this._camera != null && !this._camera.rotationQuaternion) {
  73915. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  73916. }
  73917. },
  73918. enumerable: true,
  73919. configurable: true
  73920. });
  73921. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  73922. window.addEventListener("orientationchange", this._orientationChanged);
  73923. window.addEventListener("deviceorientation", this._deviceOrientation);
  73924. //In certain cases, the attach control is called AFTER orientation was changed,
  73925. //So this is needed.
  73926. this._orientationChanged();
  73927. };
  73928. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  73929. window.removeEventListener("orientationchange", this._orientationChanged);
  73930. window.removeEventListener("deviceorientation", this._deviceOrientation);
  73931. };
  73932. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  73933. //if no device orientation provided, don't update the rotation.
  73934. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  73935. if (!this._alpha)
  73936. return;
  73937. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  73938. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  73939. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  73940. //Mirror on XY Plane
  73941. this._camera.rotationQuaternion.z *= -1;
  73942. this._camera.rotationQuaternion.w *= -1;
  73943. };
  73944. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  73945. return "FreeCameraDeviceOrientationInput";
  73946. };
  73947. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  73948. return "deviceOrientation";
  73949. };
  73950. return FreeCameraDeviceOrientationInput;
  73951. }());
  73952. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  73953. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  73954. })(BABYLON || (BABYLON = {}));
  73955. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  73956. var BABYLON;
  73957. (function (BABYLON) {
  73958. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  73959. function ArcRotateCameraVRDeviceOrientationInput() {
  73960. this.alphaCorrection = 1;
  73961. this.betaCorrection = 1;
  73962. this.gammaCorrection = 1;
  73963. this._alpha = 0;
  73964. this._gamma = 0;
  73965. this._dirty = false;
  73966. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  73967. }
  73968. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  73969. this.camera.attachControl(element, noPreventDefault);
  73970. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  73971. };
  73972. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  73973. if (evt.alpha !== null) {
  73974. this._alpha = +evt.alpha | 0;
  73975. }
  73976. if (evt.gamma !== null) {
  73977. this._gamma = +evt.gamma | 0;
  73978. }
  73979. this._dirty = true;
  73980. };
  73981. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  73982. if (this._dirty) {
  73983. this._dirty = false;
  73984. if (this._gamma < 0) {
  73985. this._gamma = 180 + this._gamma;
  73986. }
  73987. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  73988. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  73989. }
  73990. };
  73991. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  73992. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  73993. };
  73994. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  73995. return "ArcRotateCameraVRDeviceOrientationInput";
  73996. };
  73997. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  73998. return "VRDeviceOrientation";
  73999. };
  74000. return ArcRotateCameraVRDeviceOrientationInput;
  74001. }());
  74002. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74003. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74004. })(BABYLON || (BABYLON = {}));
  74005. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74006. var BABYLON;
  74007. (function (BABYLON) {
  74008. var VRCameraMetrics = /** @class */ (function () {
  74009. function VRCameraMetrics() {
  74010. this.compensateDistortion = true;
  74011. }
  74012. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74013. get: function () {
  74014. return this.hResolution / (2 * this.vResolution);
  74015. },
  74016. enumerable: true,
  74017. configurable: true
  74018. });
  74019. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74020. get: function () {
  74021. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74022. },
  74023. enumerable: true,
  74024. configurable: true
  74025. });
  74026. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74027. get: function () {
  74028. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74029. var h = (4 * meters) / this.hScreenSize;
  74030. return BABYLON.Matrix.Translation(h, 0, 0);
  74031. },
  74032. enumerable: true,
  74033. configurable: true
  74034. });
  74035. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74036. get: function () {
  74037. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74038. var h = (4 * meters) / this.hScreenSize;
  74039. return BABYLON.Matrix.Translation(-h, 0, 0);
  74040. },
  74041. enumerable: true,
  74042. configurable: true
  74043. });
  74044. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74045. get: function () {
  74046. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74047. },
  74048. enumerable: true,
  74049. configurable: true
  74050. });
  74051. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74052. get: function () {
  74053. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74054. },
  74055. enumerable: true,
  74056. configurable: true
  74057. });
  74058. VRCameraMetrics.GetDefault = function () {
  74059. var result = new VRCameraMetrics();
  74060. result.hResolution = 1280;
  74061. result.vResolution = 800;
  74062. result.hScreenSize = 0.149759993;
  74063. result.vScreenSize = 0.0935999975;
  74064. result.vScreenCenter = 0.0467999987;
  74065. result.eyeToScreenDistance = 0.0410000011;
  74066. result.lensSeparationDistance = 0.0635000020;
  74067. result.interpupillaryDistance = 0.0640000030;
  74068. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74069. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74070. result.postProcessScaleFactor = 1.714605507808412;
  74071. result.lensCenterOffset = 0.151976421;
  74072. return result;
  74073. };
  74074. return VRCameraMetrics;
  74075. }());
  74076. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74077. })(BABYLON || (BABYLON = {}));
  74078. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74079. var BABYLON;
  74080. (function (BABYLON) {
  74081. var WebVRFreeCamera = /** @class */ (function (_super) {
  74082. __extends(WebVRFreeCamera, _super);
  74083. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74084. if (webVROptions === void 0) { webVROptions = {}; }
  74085. var _this = _super.call(this, name, position, scene) || this;
  74086. _this.webVROptions = webVROptions;
  74087. _this._vrDevice = null;
  74088. _this.rawPose = null;
  74089. _this._specsVersion = "1.1";
  74090. _this._attached = false;
  74091. _this._descendants = [];
  74092. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74093. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74094. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74095. _this._standingMatrix = null;
  74096. // Represents device position and rotation in babylon space
  74097. _this.devicePosition = BABYLON.Vector3.Zero();
  74098. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74099. _this.deviceScaleFactor = 1;
  74100. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74101. _this._worldToDevice = BABYLON.Matrix.Identity();
  74102. _this.controllers = [];
  74103. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74104. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74105. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  74106. _this._defaultHeight = undefined;
  74107. _this.deviceDistanceToRoomGround = function () {
  74108. if (_this._standingMatrix && _this._defaultHeight === undefined) {
  74109. // Add standing matrix offset to get real offset from ground in room
  74110. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  74111. return _this._deviceRoomPosition.y + _this._workingVector.y;
  74112. }
  74113. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74114. return _this._defaultHeight || 0;
  74115. };
  74116. _this.useStandingMatrix = function (callback) {
  74117. if (callback === void 0) { callback = function (bool) { }; }
  74118. // Use standing matrix if availible
  74119. if (!navigator || !navigator.getVRDisplays) {
  74120. callback(false);
  74121. }
  74122. else {
  74123. navigator.getVRDisplays().then(function (displays) {
  74124. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74125. callback(false);
  74126. }
  74127. else {
  74128. _this._standingMatrix = new BABYLON.Matrix();
  74129. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74130. if (!_this.getScene().useRightHandedSystem) {
  74131. [2, 6, 8, 9, 14].forEach(function (num) {
  74132. if (_this._standingMatrix) {
  74133. _this._standingMatrix.m[num] *= -1;
  74134. }
  74135. });
  74136. }
  74137. callback(true);
  74138. }
  74139. });
  74140. }
  74141. };
  74142. _this._workingVector = BABYLON.Vector3.Zero();
  74143. _this._oneVector = BABYLON.Vector3.One();
  74144. _this._workingMatrix = BABYLON.Matrix.Identity();
  74145. _this._cache.position = BABYLON.Vector3.Zero();
  74146. if (webVROptions.defaultHeight) {
  74147. _this._defaultHeight = webVROptions.defaultHeight;
  74148. _this.position.y = _this._defaultHeight;
  74149. }
  74150. _this.minZ = 0.1;
  74151. //legacy support - the compensation boolean was removed.
  74152. if (arguments.length === 5) {
  74153. _this.webVROptions = arguments[4];
  74154. }
  74155. // default webVR options
  74156. if (_this.webVROptions.trackPosition == undefined) {
  74157. _this.webVROptions.trackPosition = true;
  74158. }
  74159. if (_this.webVROptions.controllerMeshes == undefined) {
  74160. _this.webVROptions.controllerMeshes = true;
  74161. }
  74162. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74163. _this.webVROptions.defaultLightingOnControllers = true;
  74164. }
  74165. _this.rotationQuaternion = new BABYLON.Quaternion();
  74166. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74167. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74168. }
  74169. //enable VR
  74170. var engine = _this.getEngine();
  74171. _this._onVREnabled = function (success) { if (success) {
  74172. _this.initControllers();
  74173. } };
  74174. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74175. engine.initWebVR().add(function (event) {
  74176. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74177. return;
  74178. }
  74179. _this._vrDevice = event.vrDisplay;
  74180. //reset the rig parameters.
  74181. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74182. if (_this._attached) {
  74183. _this.getEngine().enableVR();
  74184. }
  74185. });
  74186. if (typeof (VRFrameData) !== "undefined")
  74187. _this._frameData = new VRFrameData();
  74188. /**
  74189. * The idea behind the following lines:
  74190. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74191. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74192. * the second will not show it correctly.
  74193. *
  74194. * To solve this - each object that has the camera as parent will be added to a protected array.
  74195. * When the rig camera renders, it will take this array and set all of those to be its children.
  74196. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74197. * Amazing!
  74198. */
  74199. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74200. if (camera.parent === _this && _this.rigParenting) {
  74201. _this._descendants = _this.getDescendants(true, function (n) {
  74202. // don't take the cameras or the controllers!
  74203. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74204. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74205. return !isController && !isRigCamera;
  74206. });
  74207. _this._descendants.forEach(function (node) {
  74208. node.parent = camera;
  74209. });
  74210. }
  74211. });
  74212. scene.onAfterCameraRenderObservable.add(function (camera) {
  74213. if (camera.parent === _this && _this.rigParenting) {
  74214. _this._descendants.forEach(function (node) {
  74215. node.parent = _this;
  74216. });
  74217. }
  74218. });
  74219. return _this;
  74220. }
  74221. WebVRFreeCamera.prototype.dispose = function () {
  74222. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74223. _super.prototype.dispose.call(this);
  74224. };
  74225. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74226. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74227. var gp = _a[_i];
  74228. if (gp.hand === name) {
  74229. return gp;
  74230. }
  74231. }
  74232. return null;
  74233. };
  74234. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74235. get: function () {
  74236. if (!this._leftController) {
  74237. this._leftController = this.getControllerByName("left");
  74238. }
  74239. return this._leftController;
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. ;
  74245. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74246. get: function () {
  74247. if (!this._rightController) {
  74248. this._rightController = this.getControllerByName("right");
  74249. }
  74250. return this._rightController;
  74251. },
  74252. enumerable: true,
  74253. configurable: true
  74254. });
  74255. ;
  74256. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74257. if (length === void 0) { length = 100; }
  74258. if (this.leftCamera) {
  74259. // Use left eye to avoid computation to compute center on every call
  74260. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74261. }
  74262. else {
  74263. return _super.prototype.getForwardRay.call(this, length);
  74264. }
  74265. };
  74266. WebVRFreeCamera.prototype._checkInputs = function () {
  74267. if (this._vrDevice && this._vrDevice.isPresenting) {
  74268. this._vrDevice.getFrameData(this._frameData);
  74269. this.updateFromDevice(this._frameData.pose);
  74270. }
  74271. _super.prototype._checkInputs.call(this);
  74272. };
  74273. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74274. if (poseData && poseData.orientation) {
  74275. this.rawPose = poseData;
  74276. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74277. if (this.getScene().useRightHandedSystem) {
  74278. this._deviceRoomRotationQuaternion.z *= -1;
  74279. this._deviceRoomRotationQuaternion.w *= -1;
  74280. }
  74281. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74282. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74283. if (this.getScene().useRightHandedSystem) {
  74284. this._deviceRoomPosition.z *= -1;
  74285. }
  74286. }
  74287. }
  74288. };
  74289. /**
  74290. * WebVR's attach control will start broadcasting frames to the device.
  74291. * Note that in certain browsers (chrome for example) this function must be called
  74292. * within a user-interaction callback. Example:
  74293. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74294. *
  74295. * @param {HTMLElement} element
  74296. * @param {boolean} [noPreventDefault]
  74297. *
  74298. * @memberOf WebVRFreeCamera
  74299. */
  74300. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74301. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74302. this._attached = true;
  74303. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74304. if (this._vrDevice) {
  74305. this.getEngine().enableVR();
  74306. }
  74307. };
  74308. WebVRFreeCamera.prototype.detachControl = function (element) {
  74309. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74310. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74311. _super.prototype.detachControl.call(this, element);
  74312. this._attached = false;
  74313. this.getEngine().disableVR();
  74314. };
  74315. WebVRFreeCamera.prototype.getClassName = function () {
  74316. return "WebVRFreeCamera";
  74317. };
  74318. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74319. //uses the vrDisplay's "resetPose()".
  74320. //pitch and roll won't be affected.
  74321. this._vrDevice.resetPose();
  74322. };
  74323. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74324. var camLeft = this._rigCameras[0];
  74325. var camRight = this._rigCameras[1];
  74326. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74327. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74328. camLeft.position.copyFrom(this._deviceRoomPosition);
  74329. camRight.position.copyFrom(this._deviceRoomPosition);
  74330. };
  74331. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74332. var _this = this;
  74333. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74334. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74335. if (!this.updateCacheCalled) {
  74336. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74337. this.updateCacheCalled = true;
  74338. this.update();
  74339. }
  74340. // Set working vector to the device position in room space rotated by the new rotation
  74341. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74342. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74343. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74344. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74345. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74346. // Add translation from anchor position
  74347. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74348. this._workingVector.addInPlace(this.position);
  74349. this._workingVector.subtractInPlace(this._cache.position);
  74350. this._deviceToWorld.setTranslation(this._workingVector);
  74351. // Set an inverted matrix to be used when updating the camera
  74352. this._deviceToWorld.invertToRef(this._worldToDevice);
  74353. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74354. this.controllers.forEach(function (controller) {
  74355. controller._deviceToWorld = _this._deviceToWorld;
  74356. controller.update();
  74357. });
  74358. }
  74359. if (!ignoreParentClass) {
  74360. _super.prototype._updateCache.call(this);
  74361. }
  74362. this.updateCacheCalled = false;
  74363. };
  74364. WebVRFreeCamera.prototype.update = function () {
  74365. // Get current device position in babylon world
  74366. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74367. // Get current device rotation in babylon world
  74368. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74369. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74370. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74371. _super.prototype.update.call(this);
  74372. };
  74373. WebVRFreeCamera.prototype._getViewMatrix = function () {
  74374. return BABYLON.Matrix.Identity();
  74375. };
  74376. /**
  74377. * This function is called by the two RIG cameras.
  74378. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  74379. */
  74380. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  74381. var _this = this;
  74382. //WebVR 1.1
  74383. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  74384. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  74385. if (!this.getScene().useRightHandedSystem) {
  74386. [2, 6, 8, 9, 14].forEach(function (num) {
  74387. _this._webvrViewMatrix.m[num] *= -1;
  74388. });
  74389. }
  74390. // update the camera rotation matrix
  74391. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  74392. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  74393. // Computing target and final matrix
  74394. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  74395. var parentCamera = this._cameraRigParams["parentCamera"];
  74396. // should the view matrix be updated with scale and position offset?
  74397. if (parentCamera.deviceScaleFactor !== 1) {
  74398. this._webvrViewMatrix.invert();
  74399. // scale the position, if set
  74400. if (parentCamera.deviceScaleFactor) {
  74401. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  74402. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  74403. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  74404. }
  74405. this._webvrViewMatrix.invert();
  74406. }
  74407. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  74408. return this._webvrViewMatrix;
  74409. };
  74410. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  74411. var _this = this;
  74412. var parentCamera = this.parent;
  74413. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  74414. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  74415. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  74416. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  74417. //babylon compatible matrix
  74418. if (!this.getScene().useRightHandedSystem) {
  74419. [8, 9, 10, 11].forEach(function (num) {
  74420. _this._projectionMatrix.m[num] *= -1;
  74421. });
  74422. }
  74423. return this._projectionMatrix;
  74424. };
  74425. WebVRFreeCamera.prototype.initControllers = function () {
  74426. var _this = this;
  74427. this.controllers = [];
  74428. var manager = this.getScene().gamepadManager;
  74429. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74430. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74431. var webVrController = gamepad;
  74432. if (webVrController.defaultModel) {
  74433. webVrController.defaultModel.setEnabled(false);
  74434. }
  74435. if (webVrController.hand === "right") {
  74436. _this._rightController = null;
  74437. }
  74438. if (webVrController.hand === "left") {
  74439. _this._rightController = null;
  74440. }
  74441. var controllerIndex = _this.controllers.indexOf(webVrController);
  74442. if (controllerIndex !== -1) {
  74443. _this.controllers.splice(controllerIndex, 1);
  74444. }
  74445. }
  74446. });
  74447. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74448. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74449. var webVrController_1 = gamepad;
  74450. webVrController_1._deviceToWorld = _this._deviceToWorld;
  74451. if (_this.webVROptions.controllerMeshes) {
  74452. if (webVrController_1.defaultModel) {
  74453. webVrController_1.defaultModel.setEnabled(true);
  74454. }
  74455. else {
  74456. // Load the meshes
  74457. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  74458. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  74459. if (_this.webVROptions.defaultLightingOnControllers) {
  74460. if (!_this._lightOnControllers) {
  74461. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  74462. }
  74463. var activateLightOnSubMeshes_1 = function (mesh, light) {
  74464. var children = mesh.getChildren();
  74465. if (children.length !== 0) {
  74466. children.forEach(function (mesh) {
  74467. light.includedOnlyMeshes.push(mesh);
  74468. activateLightOnSubMeshes_1(mesh, light);
  74469. });
  74470. }
  74471. };
  74472. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  74473. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  74474. }
  74475. });
  74476. }
  74477. }
  74478. webVrController_1.attachToPoseControlledCamera(_this);
  74479. // since this is async - sanity check. Is the controller already stored?
  74480. if (_this.controllers.indexOf(webVrController_1) === -1) {
  74481. //add to the controllers array
  74482. _this.controllers.push(webVrController_1);
  74483. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  74484. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  74485. // So we're overriding setting left & right manually to be sure
  74486. var firstViveWandDetected = false;
  74487. for (var i = 0; i < _this.controllers.length; i++) {
  74488. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74489. if (!firstViveWandDetected) {
  74490. firstViveWandDetected = true;
  74491. _this.controllers[i].hand = "left";
  74492. }
  74493. else {
  74494. _this.controllers[i].hand = "right";
  74495. }
  74496. }
  74497. }
  74498. //did we find enough controllers? Great! let the developer know.
  74499. if (_this.controllers.length >= 2) {
  74500. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  74501. }
  74502. }
  74503. }
  74504. });
  74505. };
  74506. return WebVRFreeCamera;
  74507. }(BABYLON.FreeCamera));
  74508. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  74509. })(BABYLON || (BABYLON = {}));
  74510. //# sourceMappingURL=babylon.webVRCamera.js.map
  74511. var BABYLON;
  74512. (function (BABYLON) {
  74513. // We're mainly based on the logic defined into the FreeCamera code
  74514. /**
  74515. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  74516. * being tilted forward or back and left or right.
  74517. */
  74518. var DeviceOrientationCamera = /** @class */ (function (_super) {
  74519. __extends(DeviceOrientationCamera, _super);
  74520. /**
  74521. * Creates a new device orientation camera. @see DeviceOrientationCamera
  74522. * @param name The name of the camera
  74523. * @param position The start position camera
  74524. * @param scene The scene the camera belongs to
  74525. */
  74526. function DeviceOrientationCamera(name, position, scene) {
  74527. var _this = _super.call(this, name, position, scene) || this;
  74528. _this._quaternionCache = new BABYLON.Quaternion();
  74529. _this.inputs.addDeviceOrientation();
  74530. return _this;
  74531. }
  74532. /**
  74533. * Gets the current instance class name ("DeviceOrientationCamera").
  74534. * This helps avoiding instanceof at run time.
  74535. * @returns the class name
  74536. */
  74537. DeviceOrientationCamera.prototype.getClassName = function () {
  74538. return "DeviceOrientationCamera";
  74539. };
  74540. /**
  74541. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  74542. */
  74543. DeviceOrientationCamera.prototype._checkInputs = function () {
  74544. _super.prototype._checkInputs.call(this);
  74545. this._quaternionCache.copyFrom(this.rotationQuaternion);
  74546. if (this._initialQuaternion) {
  74547. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74548. }
  74549. };
  74550. /**
  74551. * Reset the camera to its default orientation on the specified axis only.
  74552. * @param axis The axis to reset
  74553. */
  74554. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  74555. var _this = this;
  74556. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  74557. //can only work if this camera has a rotation quaternion already.
  74558. if (!this.rotationQuaternion)
  74559. return;
  74560. if (!this._initialQuaternion) {
  74561. this._initialQuaternion = new BABYLON.Quaternion();
  74562. }
  74563. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  74564. ['x', 'y', 'z'].forEach(function (axisName) {
  74565. if (!axis[axisName]) {
  74566. _this._initialQuaternion[axisName] = 0;
  74567. }
  74568. else {
  74569. _this._initialQuaternion[axisName] *= -1;
  74570. }
  74571. });
  74572. this._initialQuaternion.normalize();
  74573. //force rotation update
  74574. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74575. };
  74576. return DeviceOrientationCamera;
  74577. }(BABYLON.FreeCamera));
  74578. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  74579. })(BABYLON || (BABYLON = {}));
  74580. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  74581. var BABYLON;
  74582. (function (BABYLON) {
  74583. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  74584. __extends(VRDeviceOrientationFreeCamera, _super);
  74585. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74586. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74587. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74588. var _this = _super.call(this, name, position, scene) || this;
  74589. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74590. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74591. return _this;
  74592. }
  74593. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  74594. return "VRDeviceOrientationFreeCamera";
  74595. };
  74596. return VRDeviceOrientationFreeCamera;
  74597. }(BABYLON.DeviceOrientationCamera));
  74598. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  74599. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  74600. __extends(VRDeviceOrientationGamepadCamera, _super);
  74601. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74602. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74603. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74604. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  74605. _this.inputs.addGamepad();
  74606. return _this;
  74607. }
  74608. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  74609. return "VRDeviceOrientationGamepadCamera";
  74610. };
  74611. return VRDeviceOrientationGamepadCamera;
  74612. }(VRDeviceOrientationFreeCamera));
  74613. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  74614. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  74615. __extends(VRDeviceOrientationArcRotateCamera, _super);
  74616. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  74617. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74618. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74619. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74620. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74621. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74622. _this.inputs.addVRDeviceOrientation();
  74623. return _this;
  74624. }
  74625. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  74626. return "VRDeviceOrientationArcRotateCamera";
  74627. };
  74628. return VRDeviceOrientationArcRotateCamera;
  74629. }(BABYLON.ArcRotateCamera));
  74630. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  74631. })(BABYLON || (BABYLON = {}));
  74632. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  74633. var BABYLON;
  74634. (function (BABYLON) {
  74635. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  74636. __extends(AnaglyphFreeCamera, _super);
  74637. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  74638. var _this = _super.call(this, name, position, scene) || this;
  74639. _this.interaxialDistance = interaxialDistance;
  74640. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74641. return _this;
  74642. }
  74643. AnaglyphFreeCamera.prototype.getClassName = function () {
  74644. return "AnaglyphFreeCamera";
  74645. };
  74646. return AnaglyphFreeCamera;
  74647. }(BABYLON.FreeCamera));
  74648. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  74649. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  74650. __extends(AnaglyphArcRotateCamera, _super);
  74651. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  74652. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74653. _this.interaxialDistance = interaxialDistance;
  74654. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74655. return _this;
  74656. }
  74657. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  74658. return "AnaglyphArcRotateCamera";
  74659. };
  74660. return AnaglyphArcRotateCamera;
  74661. }(BABYLON.ArcRotateCamera));
  74662. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  74663. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  74664. __extends(AnaglyphGamepadCamera, _super);
  74665. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  74666. var _this = _super.call(this, name, position, scene) || this;
  74667. _this.interaxialDistance = interaxialDistance;
  74668. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74669. return _this;
  74670. }
  74671. AnaglyphGamepadCamera.prototype.getClassName = function () {
  74672. return "AnaglyphGamepadCamera";
  74673. };
  74674. return AnaglyphGamepadCamera;
  74675. }(BABYLON.GamepadCamera));
  74676. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  74677. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  74678. __extends(AnaglyphUniversalCamera, _super);
  74679. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  74680. var _this = _super.call(this, name, position, scene) || this;
  74681. _this.interaxialDistance = interaxialDistance;
  74682. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74683. return _this;
  74684. }
  74685. AnaglyphUniversalCamera.prototype.getClassName = function () {
  74686. return "AnaglyphUniversalCamera";
  74687. };
  74688. return AnaglyphUniversalCamera;
  74689. }(BABYLON.UniversalCamera));
  74690. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  74691. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  74692. __extends(StereoscopicFreeCamera, _super);
  74693. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74694. var _this = _super.call(this, name, position, scene) || this;
  74695. _this.interaxialDistance = interaxialDistance;
  74696. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74697. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74698. return _this;
  74699. }
  74700. StereoscopicFreeCamera.prototype.getClassName = function () {
  74701. return "StereoscopicFreeCamera";
  74702. };
  74703. return StereoscopicFreeCamera;
  74704. }(BABYLON.FreeCamera));
  74705. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  74706. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  74707. __extends(StereoscopicArcRotateCamera, _super);
  74708. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  74709. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74710. _this.interaxialDistance = interaxialDistance;
  74711. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74712. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74713. return _this;
  74714. }
  74715. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  74716. return "StereoscopicArcRotateCamera";
  74717. };
  74718. return StereoscopicArcRotateCamera;
  74719. }(BABYLON.ArcRotateCamera));
  74720. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  74721. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  74722. __extends(StereoscopicGamepadCamera, _super);
  74723. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74724. var _this = _super.call(this, name, position, scene) || this;
  74725. _this.interaxialDistance = interaxialDistance;
  74726. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74727. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74728. return _this;
  74729. }
  74730. StereoscopicGamepadCamera.prototype.getClassName = function () {
  74731. return "StereoscopicGamepadCamera";
  74732. };
  74733. return StereoscopicGamepadCamera;
  74734. }(BABYLON.GamepadCamera));
  74735. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  74736. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  74737. __extends(StereoscopicUniversalCamera, _super);
  74738. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74739. var _this = _super.call(this, name, position, scene) || this;
  74740. _this.interaxialDistance = interaxialDistance;
  74741. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74742. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74743. return _this;
  74744. }
  74745. StereoscopicUniversalCamera.prototype.getClassName = function () {
  74746. return "StereoscopicUniversalCamera";
  74747. };
  74748. return StereoscopicUniversalCamera;
  74749. }(BABYLON.UniversalCamera));
  74750. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  74751. })(BABYLON || (BABYLON = {}));
  74752. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  74753. var BABYLON;
  74754. (function (BABYLON) {
  74755. var VRExperienceHelper = /** @class */ (function () {
  74756. function VRExperienceHelper(scene, webVROptions) {
  74757. if (webVROptions === void 0) { webVROptions = {}; }
  74758. var _this = this;
  74759. this.webVROptions = webVROptions;
  74760. // Can the system support WebVR, even if a headset isn't plugged in?
  74761. this._webVRsupported = false;
  74762. // If WebVR is supported, is a headset plugged in and are we ready to present?
  74763. this._webVRready = false;
  74764. // Are we waiting for the requestPresent callback to complete?
  74765. this._webVRrequesting = false;
  74766. // Are we presenting to the headset right now?
  74767. this._webVRpresenting = false;
  74768. // Are we presenting in the fullscreen fallback?
  74769. this._fullscreenVRpresenting = false;
  74770. /**
  74771. * Observable raised when entering VR.
  74772. */
  74773. this.onEnteringVRObservable = new BABYLON.Observable();
  74774. /**
  74775. * Observable raised when exiting VR.
  74776. */
  74777. this.onExitingVRObservable = new BABYLON.Observable();
  74778. /**
  74779. * Observable raised when controller mesh is loaded.
  74780. */
  74781. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74782. this._useCustomVRButton = false;
  74783. this._teleportationRequested = false;
  74784. this._teleportationEnabledOnLeftController = false;
  74785. this._teleportationEnabledOnRightController = false;
  74786. this._interactionsEnabledOnLeftController = false;
  74787. this._interactionsEnabledOnRightController = false;
  74788. this._leftControllerReady = false;
  74789. this._rightControllerReady = false;
  74790. this._floorMeshesCollection = [];
  74791. this._teleportationAllowed = false;
  74792. this._rotationAllowed = true;
  74793. this._teleportationRequestInitiated = false;
  74794. this._teleportationBackRequestInitiated = false;
  74795. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  74796. this._rotationRightAsked = false;
  74797. this._rotationLeftAsked = false;
  74798. this._isDefaultTeleportationTarget = true;
  74799. this._teleportationFillColor = "#444444";
  74800. this._teleportationBorderColor = "#FFFFFF";
  74801. this._rotationAngle = 0;
  74802. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  74803. this._padSensibilityUp = 0.65;
  74804. this._padSensibilityDown = 0.35;
  74805. /**
  74806. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  74807. */
  74808. this.onNewMeshSelected = new BABYLON.Observable();
  74809. /**
  74810. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  74811. */
  74812. this.onNewMeshPicked = new BABYLON.Observable();
  74813. /**
  74814. * Observable raised before camera teleportation
  74815. */
  74816. this.onBeforeCameraTeleport = new BABYLON.Observable();
  74817. /**
  74818. * Observable raised after camera teleportation
  74819. */
  74820. this.onAfterCameraTeleport = new BABYLON.Observable();
  74821. /**
  74822. * Observable raised when current selected mesh gets unselected
  74823. */
  74824. this.onSelectedMeshUnselected = new BABYLON.Observable();
  74825. /**
  74826. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  74827. */
  74828. this.teleportationEnabled = true;
  74829. this._pointerDownOnMeshAsked = false;
  74830. this._isActionableMesh = false;
  74831. this._teleportationInitialized = false;
  74832. this._interactionsEnabled = false;
  74833. this._interactionsRequested = false;
  74834. this._displayGaze = true;
  74835. this._displayLaserPointer = true;
  74836. this._dpadPressed = true;
  74837. this._onResize = function () {
  74838. _this.moveButtonToBottomRight();
  74839. if (_this._fullscreenVRpresenting && _this._webVRready) {
  74840. _this.exitVR();
  74841. }
  74842. };
  74843. this._onFullscreenChange = function () {
  74844. if (document.fullscreen !== undefined) {
  74845. _this._fullscreenVRpresenting = document.fullscreen;
  74846. }
  74847. else if (document.mozFullScreen !== undefined) {
  74848. _this._fullscreenVRpresenting = document.mozFullScreen;
  74849. }
  74850. else if (document.webkitIsFullScreen !== undefined) {
  74851. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  74852. }
  74853. else if (document.msIsFullScreen !== undefined) {
  74854. _this._fullscreenVRpresenting = document.msIsFullScreen;
  74855. }
  74856. if (!_this._fullscreenVRpresenting && _this._canvas) {
  74857. _this.exitVR();
  74858. if (!_this._useCustomVRButton) {
  74859. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  74860. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  74861. }
  74862. }
  74863. };
  74864. this.beforeRender = function () {
  74865. _this._castRayAndSelectObject();
  74866. };
  74867. this._onNewGamepadConnected = function (gamepad) {
  74868. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74869. if (gamepad.leftStick) {
  74870. gamepad.onleftstickchanged(function (stickValues) {
  74871. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  74872. // Listening to classic/xbox gamepad only if no VR controller is active
  74873. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  74874. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  74875. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  74876. _this._checkTeleportWithRay(stickValues);
  74877. _this._checkTeleportBackwards(stickValues);
  74878. }
  74879. }
  74880. });
  74881. }
  74882. if (gamepad.rightStick) {
  74883. gamepad.onrightstickchanged(function (stickValues) {
  74884. if (_this._teleportationInitialized) {
  74885. _this._checkRotate(stickValues);
  74886. }
  74887. });
  74888. }
  74889. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  74890. gamepad.onbuttondown(function (buttonPressed) {
  74891. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  74892. _this._selectionPointerDown();
  74893. }
  74894. });
  74895. gamepad.onbuttonup(function (buttonPressed) {
  74896. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  74897. _this._selectionPointerUp();
  74898. }
  74899. });
  74900. }
  74901. }
  74902. else {
  74903. var webVRController = gamepad;
  74904. _this._tryEnableInteractionOnController(webVRController);
  74905. }
  74906. };
  74907. // 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
  74908. this._tryEnableInteractionOnController = function (webVRController) {
  74909. if (webVRController.hand === "left") {
  74910. _this._leftControllerReady = true;
  74911. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  74912. _this._enableInteractionOnController(webVRController);
  74913. }
  74914. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  74915. _this._enableTeleportationOnController(webVRController);
  74916. }
  74917. }
  74918. if (webVRController.hand === "right") {
  74919. _this._rightControllerReady = true;
  74920. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  74921. _this._enableInteractionOnController(webVRController);
  74922. }
  74923. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  74924. _this._enableTeleportationOnController(webVRController);
  74925. }
  74926. }
  74927. };
  74928. this._onNewGamepadDisconnected = function (gamepad) {
  74929. if (gamepad instanceof BABYLON.WebVRController) {
  74930. if (gamepad.hand === "left") {
  74931. _this._interactionsEnabledOnLeftController = false;
  74932. _this._teleportationEnabledOnLeftController = false;
  74933. _this._leftControllerReady = false;
  74934. if (_this._leftLaserPointer) {
  74935. _this._leftLaserPointer.dispose();
  74936. }
  74937. }
  74938. if (gamepad.hand === "right") {
  74939. _this._interactionsEnabledOnRightController = false;
  74940. _this._teleportationEnabledOnRightController = false;
  74941. _this._rightControllerReady = false;
  74942. if (_this._rightLaserPointer) {
  74943. _this._rightLaserPointer.dispose();
  74944. }
  74945. }
  74946. }
  74947. };
  74948. this._workingVector = BABYLON.Vector3.Zero();
  74949. this._workingQuaternion = BABYLON.Quaternion.Identity();
  74950. this._workingMatrix = BABYLON.Matrix.Identity();
  74951. this._scene = scene;
  74952. this._canvas = scene.getEngine().getRenderingCanvas();
  74953. // Parse options
  74954. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  74955. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  74956. }
  74957. if (webVROptions.createDeviceOrientationCamera === undefined) {
  74958. webVROptions.createDeviceOrientationCamera = true;
  74959. }
  74960. if (webVROptions.defaultHeight === undefined) {
  74961. webVROptions.defaultHeight = 1.7;
  74962. }
  74963. if (webVROptions.useCustomVRButton) {
  74964. this._useCustomVRButton = true;
  74965. if (webVROptions.customVRButton) {
  74966. this._btnVR = webVROptions.customVRButton;
  74967. }
  74968. }
  74969. if (webVROptions.rayLength) {
  74970. this._rayLength = webVROptions.rayLength;
  74971. }
  74972. this._defaultHeight = webVROptions.defaultHeight;
  74973. // Set position
  74974. if (this._scene.activeCamera) {
  74975. this._position = this._scene.activeCamera.position.clone();
  74976. }
  74977. else {
  74978. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  74979. }
  74980. // Set non-vr camera
  74981. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  74982. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  74983. // Copy data from existing camera
  74984. if (this._scene.activeCamera) {
  74985. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  74986. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  74987. // Set rotation from previous camera
  74988. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  74989. var targetCamera = this._scene.activeCamera;
  74990. if (targetCamera.rotationQuaternion) {
  74991. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  74992. }
  74993. else {
  74994. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  74995. }
  74996. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  74997. }
  74998. }
  74999. this._scene.activeCamera = this._deviceOrientationCamera;
  75000. if (this._canvas) {
  75001. this._scene.activeCamera.attachControl(this._canvas);
  75002. }
  75003. }
  75004. else {
  75005. this._existingCamera = this._scene.activeCamera;
  75006. }
  75007. // Create VR cameras
  75008. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75009. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75010. }
  75011. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75012. this._webVRCamera.useStandingMatrix();
  75013. // Create default button
  75014. if (!this._useCustomVRButton) {
  75015. this._btnVR = document.createElement("BUTTON");
  75016. this._btnVR.className = "babylonVRicon";
  75017. this._btnVR.id = "babylonVRiconbtn";
  75018. this._btnVR.title = "Click to switch to VR";
  75019. 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) }";
  75020. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75021. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75022. // css += ".babylonVRicon.vrdisplaysupported { }";
  75023. // css += ".babylonVRicon.vrdisplayready { }";
  75024. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75025. var style = document.createElement('style');
  75026. style.appendChild(document.createTextNode(css));
  75027. document.getElementsByTagName('head')[0].appendChild(style);
  75028. this.moveButtonToBottomRight();
  75029. }
  75030. // VR button click event
  75031. if (this._btnVR) {
  75032. this._btnVR.addEventListener("click", function () {
  75033. if (!_this.isInVRMode) {
  75034. _this.enterVR();
  75035. }
  75036. else {
  75037. _this.exitVR();
  75038. }
  75039. });
  75040. }
  75041. // Window events
  75042. window.addEventListener("resize", this._onResize);
  75043. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75044. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75045. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75046. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75047. // Display vr button when headset is connected
  75048. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75049. this.displayVRButton();
  75050. }
  75051. else {
  75052. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75053. if (e.vrDisplay) {
  75054. _this.displayVRButton();
  75055. }
  75056. });
  75057. }
  75058. // Exiting VR mode using 'ESC' key on desktop
  75059. this._onKeyDown = function (event) {
  75060. if (event.keyCode === 27 && _this.isInVRMode) {
  75061. _this.exitVR();
  75062. }
  75063. };
  75064. document.addEventListener("keydown", this._onKeyDown);
  75065. // Exiting VR mode double tapping the touch screen
  75066. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75067. if (_this.isInVRMode) {
  75068. _this.exitVR();
  75069. if (_this._fullscreenVRpresenting) {
  75070. _this._scene.getEngine().switchFullscreen(true);
  75071. }
  75072. }
  75073. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75074. // Listen for WebVR display changes
  75075. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75076. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75077. this._onVRRequestPresentStart = function () {
  75078. _this._webVRrequesting = true;
  75079. _this.updateButtonVisibility();
  75080. };
  75081. this._onVRRequestPresentComplete = function (success) {
  75082. _this._webVRrequesting = false;
  75083. _this.updateButtonVisibility();
  75084. };
  75085. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75086. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75087. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75088. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75089. scene.onDisposeObservable.add(function () {
  75090. _this.dispose();
  75091. });
  75092. // Gamepad connection events
  75093. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75094. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75095. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75096. this.updateButtonVisibility();
  75097. //create easing functions
  75098. this._circleEase = new BABYLON.CircleEase();
  75099. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75100. }
  75101. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75102. /** Return this.onEnteringVRObservable
  75103. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75104. */
  75105. get: function () {
  75106. return this.onEnteringVRObservable;
  75107. },
  75108. enumerable: true,
  75109. configurable: true
  75110. });
  75111. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75112. /** Return this.onExitingVRObservable
  75113. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75114. */
  75115. get: function () {
  75116. return this.onExitingVRObservable;
  75117. },
  75118. enumerable: true,
  75119. configurable: true
  75120. });
  75121. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75122. /** Return this.onControllerMeshLoadedObservable
  75123. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75124. */
  75125. get: function () {
  75126. return this.onControllerMeshLoadedObservable;
  75127. },
  75128. enumerable: true,
  75129. configurable: true
  75130. });
  75131. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75132. get: function () {
  75133. return this._teleportationTarget;
  75134. },
  75135. set: function (value) {
  75136. if (value) {
  75137. value.name = "teleportationTarget";
  75138. this._isDefaultTeleportationTarget = false;
  75139. this._teleportationTarget = value;
  75140. }
  75141. },
  75142. enumerable: true,
  75143. configurable: true
  75144. });
  75145. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75146. get: function () {
  75147. return this._displayGaze;
  75148. },
  75149. set: function (value) {
  75150. this._displayGaze = value;
  75151. if (!value) {
  75152. this._gazeTracker.isVisible = false;
  75153. }
  75154. },
  75155. enumerable: true,
  75156. configurable: true
  75157. });
  75158. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75159. get: function () {
  75160. return this._displayLaserPointer;
  75161. },
  75162. set: function (value) {
  75163. this._displayLaserPointer = value;
  75164. if (!value) {
  75165. if (this._rightLaserPointer) {
  75166. this._rightLaserPointer.isVisible = false;
  75167. }
  75168. if (this._leftLaserPointer) {
  75169. this._leftLaserPointer.isVisible = false;
  75170. }
  75171. }
  75172. else {
  75173. if (this._rightLaserPointer) {
  75174. this._rightLaserPointer.isVisible = true;
  75175. }
  75176. else if (this._leftLaserPointer) {
  75177. this._leftLaserPointer.isVisible = true;
  75178. }
  75179. }
  75180. },
  75181. enumerable: true,
  75182. configurable: true
  75183. });
  75184. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75185. get: function () {
  75186. return this._deviceOrientationCamera;
  75187. },
  75188. enumerable: true,
  75189. configurable: true
  75190. });
  75191. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75192. // Based on the current WebVR support, returns the current VR camera used
  75193. get: function () {
  75194. if (this._webVRready) {
  75195. return this._webVRCamera;
  75196. }
  75197. else {
  75198. return this._scene.activeCamera;
  75199. }
  75200. },
  75201. enumerable: true,
  75202. configurable: true
  75203. });
  75204. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75205. get: function () {
  75206. return this._webVRCamera;
  75207. },
  75208. enumerable: true,
  75209. configurable: true
  75210. });
  75211. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75212. get: function () {
  75213. return this._vrDeviceOrientationCamera;
  75214. },
  75215. enumerable: true,
  75216. configurable: true
  75217. });
  75218. // Raised when one of the controller has loaded successfully its associated default mesh
  75219. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75220. this._tryEnableInteractionOnController(webVRController);
  75221. try {
  75222. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75223. }
  75224. catch (err) {
  75225. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75226. }
  75227. };
  75228. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75229. /**
  75230. * Gets a value indicating if we are currently in VR mode.
  75231. */
  75232. get: function () {
  75233. return this._webVRpresenting || this._fullscreenVRpresenting;
  75234. },
  75235. enumerable: true,
  75236. configurable: true
  75237. });
  75238. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75239. var vrDisplay = this._scene.getEngine().getVRDevice();
  75240. if (vrDisplay) {
  75241. var wasPresenting = this._webVRpresenting;
  75242. // A VR display is connected
  75243. this._webVRpresenting = vrDisplay.isPresenting;
  75244. if (wasPresenting && !this._webVRpresenting)
  75245. this.exitVR();
  75246. }
  75247. else {
  75248. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75249. }
  75250. this.updateButtonVisibility();
  75251. };
  75252. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75253. this._webVRsupported = eventArgs.vrSupported;
  75254. this._webVRready = !!eventArgs.vrDisplay;
  75255. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75256. this.updateButtonVisibility();
  75257. };
  75258. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75259. if (this._canvas && !this._useCustomVRButton) {
  75260. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75261. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75262. }
  75263. };
  75264. VRExperienceHelper.prototype.displayVRButton = function () {
  75265. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75266. document.body.appendChild(this._btnVR);
  75267. this._btnVRDisplayed = true;
  75268. }
  75269. };
  75270. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75271. if (!this._btnVR || this._useCustomVRButton) {
  75272. return;
  75273. }
  75274. this._btnVR.className = "babylonVRicon";
  75275. if (this.isInVRMode) {
  75276. this._btnVR.className += " vrdisplaypresenting";
  75277. }
  75278. else {
  75279. if (this._webVRready)
  75280. this._btnVR.className += " vrdisplayready";
  75281. if (this._webVRsupported)
  75282. this._btnVR.className += " vrdisplaysupported";
  75283. if (this._webVRrequesting)
  75284. this._btnVR.className += " vrdisplayrequesting";
  75285. }
  75286. };
  75287. /**
  75288. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75289. * Otherwise, will use the fullscreen API.
  75290. */
  75291. VRExperienceHelper.prototype.enterVR = function () {
  75292. if (this.onEnteringVRObservable) {
  75293. try {
  75294. this.onEnteringVRObservable.notifyObservers(this);
  75295. }
  75296. catch (err) {
  75297. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75298. }
  75299. }
  75300. if (this._scene.activeCamera) {
  75301. this._position = this._scene.activeCamera.position.clone();
  75302. // make sure that we return to the last active camera
  75303. this._existingCamera = this._scene.activeCamera;
  75304. }
  75305. if (this._webVRrequesting)
  75306. return;
  75307. // If WebVR is supported and a headset is connected
  75308. if (this._webVRready) {
  75309. if (!this._webVRpresenting) {
  75310. this._webVRCamera.position = this._position;
  75311. this._scene.activeCamera = this._webVRCamera;
  75312. }
  75313. }
  75314. else if (this._vrDeviceOrientationCamera) {
  75315. this._vrDeviceOrientationCamera.position = this._position;
  75316. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75317. this._scene.getEngine().switchFullscreen(true);
  75318. this.updateButtonVisibility();
  75319. }
  75320. if (this._scene.activeCamera && this._canvas) {
  75321. this._scene.activeCamera.attachControl(this._canvas);
  75322. }
  75323. if (this._interactionsEnabled) {
  75324. this._scene.registerBeforeRender(this.beforeRender);
  75325. }
  75326. };
  75327. /**
  75328. * Attempt to exit VR, or fullscreen.
  75329. */
  75330. VRExperienceHelper.prototype.exitVR = function () {
  75331. if (this.onExitingVRObservable) {
  75332. try {
  75333. this.onExitingVRObservable.notifyObservers(this);
  75334. }
  75335. catch (err) {
  75336. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  75337. }
  75338. }
  75339. if (this._webVRpresenting) {
  75340. this._scene.getEngine().disableVR();
  75341. }
  75342. if (this._scene.activeCamera) {
  75343. this._position = this._scene.activeCamera.position.clone();
  75344. }
  75345. if (this._deviceOrientationCamera) {
  75346. this._deviceOrientationCamera.position = this._position;
  75347. this._scene.activeCamera = this._deviceOrientationCamera;
  75348. if (this._canvas) {
  75349. this._scene.activeCamera.attachControl(this._canvas);
  75350. }
  75351. }
  75352. else if (this._existingCamera) {
  75353. this._existingCamera.position = this._position;
  75354. this._scene.activeCamera = this._existingCamera;
  75355. }
  75356. this.updateButtonVisibility();
  75357. if (this._interactionsEnabled) {
  75358. this._scene.unregisterBeforeRender(this.beforeRender);
  75359. }
  75360. };
  75361. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  75362. get: function () {
  75363. return this._position;
  75364. },
  75365. set: function (value) {
  75366. this._position = value;
  75367. if (this._scene.activeCamera) {
  75368. this._scene.activeCamera.position = value;
  75369. }
  75370. },
  75371. enumerable: true,
  75372. configurable: true
  75373. });
  75374. VRExperienceHelper.prototype.enableInteractions = function () {
  75375. var _this = this;
  75376. if (!this._interactionsEnabled) {
  75377. this._interactionsRequested = true;
  75378. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75379. this._enableInteractionOnController(this._webVRCamera.leftController);
  75380. }
  75381. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75382. this._enableInteractionOnController(this._webVRCamera.rightController);
  75383. }
  75384. this._createGazeTracker();
  75385. this.raySelectionPredicate = function (mesh) {
  75386. return mesh.isVisible;
  75387. };
  75388. this.meshSelectionPredicate = function (mesh) {
  75389. return true;
  75390. };
  75391. this._raySelectionPredicate = function (mesh) {
  75392. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  75393. && mesh.name.indexOf("teleportationTarget") === -1
  75394. && mesh.name.indexOf("torusTeleportation") === -1
  75395. && mesh.name.indexOf("laserPointer") === -1)) {
  75396. return _this.raySelectionPredicate(mesh);
  75397. }
  75398. return false;
  75399. };
  75400. this._interactionsEnabled = true;
  75401. }
  75402. };
  75403. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  75404. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  75405. if (this._floorMeshesCollection[i].id === mesh.id) {
  75406. return true;
  75407. }
  75408. }
  75409. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  75410. return true;
  75411. }
  75412. return false;
  75413. };
  75414. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  75415. if (!this._floorMeshesCollection) {
  75416. return;
  75417. }
  75418. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  75419. return;
  75420. }
  75421. this._floorMeshesCollection.push(floorMesh);
  75422. };
  75423. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  75424. if (!this._floorMeshesCollection) {
  75425. return;
  75426. }
  75427. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  75428. if (meshIndex !== -1) {
  75429. this._floorMeshesCollection.splice(meshIndex, 1);
  75430. }
  75431. };
  75432. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  75433. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  75434. if (!this._teleportationInitialized) {
  75435. this._teleportationRequested = true;
  75436. this.enableInteractions();
  75437. if (vrTeleportationOptions.floorMeshName) {
  75438. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  75439. }
  75440. if (vrTeleportationOptions.floorMeshes) {
  75441. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  75442. }
  75443. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75444. this._enableTeleportationOnController(this._webVRCamera.leftController);
  75445. }
  75446. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75447. this._enableTeleportationOnController(this._webVRCamera.rightController);
  75448. }
  75449. // Creates an image processing post process for the vignette not relying
  75450. // on the main scene configuration for image processing to reduce setup and spaces
  75451. // (gamma/linear) conflicts.
  75452. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  75453. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75454. imageProcessingConfiguration.vignetteEnabled = true;
  75455. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  75456. this._webVRCamera.detachPostProcess(this._postProcessMove);
  75457. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  75458. this._teleportationInitialized = true;
  75459. if (this._isDefaultTeleportationTarget) {
  75460. this._createTeleportationCircles();
  75461. }
  75462. }
  75463. };
  75464. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  75465. var _this = this;
  75466. var controllerMesh = webVRController.mesh;
  75467. if (controllerMesh) {
  75468. var makeNotPick = function (root) {
  75469. root.name += " laserPointer";
  75470. root.getChildMeshes().forEach(function (c) {
  75471. makeNotPick(c);
  75472. });
  75473. };
  75474. makeNotPick(controllerMesh);
  75475. var childMeshes = controllerMesh.getChildMeshes();
  75476. for (var i = 0; i < childMeshes.length; i++) {
  75477. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  75478. controllerMesh = childMeshes[i];
  75479. break;
  75480. }
  75481. }
  75482. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  75483. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  75484. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75485. laserPointerMaterial.alpha = 0.6;
  75486. laserPointer.material = laserPointerMaterial;
  75487. laserPointer.rotation.x = Math.PI / 2;
  75488. laserPointer.parent = controllerMesh;
  75489. laserPointer.position.z = -0.5;
  75490. laserPointer.isVisible = false;
  75491. if (webVRController.hand === "left") {
  75492. this._leftLaserPointer = laserPointer;
  75493. this._interactionsEnabledOnLeftController = true;
  75494. if (!this._rightLaserPointer) {
  75495. this._leftLaserPointer.isVisible = true;
  75496. }
  75497. }
  75498. else {
  75499. this._rightLaserPointer = laserPointer;
  75500. this._interactionsEnabledOnRightController = true;
  75501. if (!this._leftLaserPointer) {
  75502. this._rightLaserPointer.isVisible = true;
  75503. }
  75504. }
  75505. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  75506. // Enabling / disabling laserPointer
  75507. if (_this._displayLaserPointer && stateObject.value === 1) {
  75508. laserPointer.isVisible = !laserPointer.isVisible;
  75509. // Laser pointer can only be active on left or right, not both at the same time
  75510. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  75511. _this._rightLaserPointer.isVisible = false;
  75512. }
  75513. else if (_this._leftLaserPointer) {
  75514. _this._leftLaserPointer.isVisible = false;
  75515. }
  75516. }
  75517. });
  75518. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  75519. if (!_this._pointerDownOnMeshAsked) {
  75520. if (stateObject.value > _this._padSensibilityUp) {
  75521. _this._selectionPointerDown();
  75522. }
  75523. }
  75524. else if (stateObject.value < _this._padSensibilityDown) {
  75525. _this._selectionPointerUp();
  75526. }
  75527. });
  75528. }
  75529. };
  75530. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  75531. if (webVRController === void 0) { webVRController = null; }
  75532. if (!this._teleportationRequestInitiated) {
  75533. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  75534. if (webVRController) {
  75535. // If laser pointer wasn't enabled yet
  75536. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  75537. this._leftLaserPointer.isVisible = true;
  75538. if (this._rightLaserPointer) {
  75539. this._rightLaserPointer.isVisible = false;
  75540. }
  75541. }
  75542. else if (this._displayLaserPointer && this._rightLaserPointer) {
  75543. this._rightLaserPointer.isVisible = true;
  75544. if (this._leftLaserPointer) {
  75545. this._leftLaserPointer.isVisible = false;
  75546. }
  75547. }
  75548. }
  75549. this._teleportationRequestInitiated = true;
  75550. }
  75551. }
  75552. else {
  75553. // Listening to the proper controller values changes to confirm teleportation
  75554. if (webVRController == null
  75555. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  75556. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  75557. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  75558. if (this._teleportationAllowed) {
  75559. this._teleportationAllowed = false;
  75560. this._teleportCamera();
  75561. }
  75562. this._teleportationRequestInitiated = false;
  75563. }
  75564. }
  75565. }
  75566. };
  75567. VRExperienceHelper.prototype._selectionPointerDown = function () {
  75568. this._pointerDownOnMeshAsked = true;
  75569. if (this._currentMeshSelected && this._currentHit) {
  75570. this._scene.simulatePointerDown(this._currentHit);
  75571. }
  75572. };
  75573. VRExperienceHelper.prototype._selectionPointerUp = function () {
  75574. if (this._currentMeshSelected && this._currentHit) {
  75575. this._scene.simulatePointerUp(this._currentHit);
  75576. }
  75577. this._pointerDownOnMeshAsked = false;
  75578. };
  75579. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  75580. // Only rotate when user is not currently selecting a teleportation location
  75581. if (this._teleportationRequestInitiated) {
  75582. return;
  75583. }
  75584. if (!this._rotationLeftAsked) {
  75585. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  75586. this._rotationLeftAsked = true;
  75587. if (this._rotationAllowed) {
  75588. this._rotateCamera(false);
  75589. }
  75590. }
  75591. }
  75592. else {
  75593. if (stateObject.x > -this._padSensibilityDown) {
  75594. this._rotationLeftAsked = false;
  75595. }
  75596. }
  75597. if (!this._rotationRightAsked) {
  75598. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  75599. this._rotationRightAsked = true;
  75600. if (this._rotationAllowed) {
  75601. this._rotateCamera(true);
  75602. }
  75603. }
  75604. }
  75605. else {
  75606. if (stateObject.x < this._padSensibilityDown) {
  75607. this._rotationRightAsked = false;
  75608. }
  75609. }
  75610. };
  75611. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  75612. // Only teleport backwards when user is not currently selecting a teleportation location
  75613. if (this._teleportationRequestInitiated) {
  75614. return;
  75615. }
  75616. // Teleport backwards
  75617. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  75618. if (!this._teleportationBackRequestInitiated) {
  75619. if (!this.currentVRCamera) {
  75620. return;
  75621. }
  75622. // Get rotation and position of the current camera
  75623. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  75624. var position = this.currentVRCamera.position;
  75625. // If the camera has device position, use that instead
  75626. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  75627. rotation = this.currentVRCamera.deviceRotationQuaternion;
  75628. position = this.currentVRCamera.devicePosition;
  75629. }
  75630. // Get matrix with only the y rotation of the device rotation
  75631. rotation.toEulerAnglesToRef(this._workingVector);
  75632. this._workingVector.z = 0;
  75633. this._workingVector.x = 0;
  75634. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  75635. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  75636. // Rotate backwards ray by device rotation to cast at the ground behind the user
  75637. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  75638. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  75639. var ray = new BABYLON.Ray(position, this._workingVector);
  75640. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75641. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  75642. this._teleportCamera(hit.pickedPoint);
  75643. }
  75644. this._teleportationBackRequestInitiated = true;
  75645. }
  75646. }
  75647. else {
  75648. this._teleportationBackRequestInitiated = false;
  75649. }
  75650. };
  75651. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  75652. var _this = this;
  75653. var controllerMesh = webVRController.mesh;
  75654. if (controllerMesh) {
  75655. if (webVRController.hand === "left") {
  75656. if (!this._interactionsEnabledOnLeftController) {
  75657. this._enableInteractionOnController(webVRController);
  75658. }
  75659. this._teleportationEnabledOnLeftController = true;
  75660. }
  75661. else {
  75662. if (!this._interactionsEnabledOnRightController) {
  75663. this._enableInteractionOnController(webVRController);
  75664. }
  75665. this._teleportationEnabledOnRightController = true;
  75666. }
  75667. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75668. this._dpadPressed = false;
  75669. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  75670. _this._dpadPressed = stateObject.pressed;
  75671. if (!_this._dpadPressed) {
  75672. _this._rotationLeftAsked = false;
  75673. _this._rotationRightAsked = false;
  75674. _this._teleportationBackRequestInitiated = false;
  75675. }
  75676. });
  75677. }
  75678. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  75679. if (_this.teleportationEnabled) {
  75680. _this._checkTeleportBackwards(stateObject);
  75681. _this._checkTeleportWithRay(stateObject, webVRController);
  75682. }
  75683. _this._checkRotate(stateObject);
  75684. });
  75685. }
  75686. };
  75687. // Gaze support used to point to teleport or to interact with an object
  75688. VRExperienceHelper.prototype._createGazeTracker = function () {
  75689. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  75690. this._gazeTracker.bakeCurrentTransformIntoVertices();
  75691. this._gazeTracker.isPickable = false;
  75692. this._gazeTracker.isVisible = false;
  75693. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  75694. targetMat.specularColor = BABYLON.Color3.Black();
  75695. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75696. targetMat.backFaceCulling = false;
  75697. this._gazeTracker.material = targetMat;
  75698. };
  75699. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  75700. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  75701. this._teleportationTarget.isPickable = false;
  75702. var length = 512;
  75703. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  75704. dynamicTexture.hasAlpha = true;
  75705. var context = dynamicTexture.getContext();
  75706. var centerX = length / 2;
  75707. var centerY = length / 2;
  75708. var radius = 200;
  75709. context.beginPath();
  75710. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  75711. context.fillStyle = this._teleportationFillColor;
  75712. context.fill();
  75713. context.lineWidth = 10;
  75714. context.strokeStyle = this._teleportationBorderColor;
  75715. context.stroke();
  75716. context.closePath();
  75717. dynamicTexture.update();
  75718. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  75719. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  75720. this._teleportationTarget.material = teleportationCircleMaterial;
  75721. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  75722. torus.isPickable = false;
  75723. torus.parent = this._teleportationTarget;
  75724. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75725. var keys = [];
  75726. keys.push({
  75727. frame: 0,
  75728. value: 0
  75729. });
  75730. keys.push({
  75731. frame: 30,
  75732. value: 0.4
  75733. });
  75734. keys.push({
  75735. frame: 60,
  75736. value: 0
  75737. });
  75738. animationInnerCircle.setKeys(keys);
  75739. var easingFunction = new BABYLON.SineEase();
  75740. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75741. animationInnerCircle.setEasingFunction(easingFunction);
  75742. torus.animations = [];
  75743. torus.animations.push(animationInnerCircle);
  75744. this._scene.beginAnimation(torus, 0, 60, true);
  75745. this._hideTeleportationTarget();
  75746. };
  75747. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  75748. if (this._teleportationInitialized) {
  75749. this._teleportationTarget.isVisible = true;
  75750. if (this._isDefaultTeleportationTarget) {
  75751. this._teleportationTarget.getChildren()[0].isVisible = true;
  75752. }
  75753. }
  75754. };
  75755. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  75756. if (this._teleportationInitialized) {
  75757. this._teleportationTarget.isVisible = false;
  75758. if (this._isDefaultTeleportationTarget) {
  75759. this._teleportationTarget.getChildren()[0].isVisible = false;
  75760. }
  75761. }
  75762. };
  75763. VRExperienceHelper.prototype._rotateCamera = function (right) {
  75764. var _this = this;
  75765. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75766. return;
  75767. }
  75768. if (right) {
  75769. this._rotationAngle++;
  75770. }
  75771. else {
  75772. this._rotationAngle--;
  75773. }
  75774. this.currentVRCamera.animations = [];
  75775. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  75776. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75777. var animationRotationKeys = [];
  75778. animationRotationKeys.push({
  75779. frame: 0,
  75780. value: this.currentVRCamera.rotationQuaternion
  75781. });
  75782. animationRotationKeys.push({
  75783. frame: 6,
  75784. value: target
  75785. });
  75786. animationRotation.setKeys(animationRotationKeys);
  75787. animationRotation.setEasingFunction(this._circleEase);
  75788. this.currentVRCamera.animations.push(animationRotation);
  75789. this._postProcessMove.animations = [];
  75790. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75791. var vignetteWeightKeys = [];
  75792. vignetteWeightKeys.push({
  75793. frame: 0,
  75794. value: 0
  75795. });
  75796. vignetteWeightKeys.push({
  75797. frame: 3,
  75798. value: 4
  75799. });
  75800. vignetteWeightKeys.push({
  75801. frame: 6,
  75802. value: 0
  75803. });
  75804. animationPP.setKeys(vignetteWeightKeys);
  75805. animationPP.setEasingFunction(this._circleEase);
  75806. this._postProcessMove.animations.push(animationPP);
  75807. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75808. var vignetteStretchKeys = [];
  75809. vignetteStretchKeys.push({
  75810. frame: 0,
  75811. value: 0
  75812. });
  75813. vignetteStretchKeys.push({
  75814. frame: 3,
  75815. value: 10
  75816. });
  75817. vignetteStretchKeys.push({
  75818. frame: 6,
  75819. value: 0
  75820. });
  75821. animationPP2.setKeys(vignetteStretchKeys);
  75822. animationPP2.setEasingFunction(this._circleEase);
  75823. this._postProcessMove.animations.push(animationPP2);
  75824. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  75825. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  75826. this._webVRCamera.attachPostProcess(this._postProcessMove);
  75827. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  75828. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  75829. });
  75830. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  75831. };
  75832. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  75833. if (hit.pickedPoint) {
  75834. this._teleportationAllowed = true;
  75835. if (this._teleportationRequestInitiated) {
  75836. this._displayTeleportationTarget();
  75837. }
  75838. else {
  75839. this._hideTeleportationTarget();
  75840. }
  75841. this._haloCenter.copyFrom(hit.pickedPoint);
  75842. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  75843. var pickNormal = hit.getNormal(true, false);
  75844. if (pickNormal) {
  75845. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  75846. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  75847. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  75848. }
  75849. this._teleportationTarget.position.y += 0.1;
  75850. }
  75851. };
  75852. VRExperienceHelper.prototype._teleportCamera = function (location) {
  75853. var _this = this;
  75854. if (location === void 0) { location = null; }
  75855. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75856. return;
  75857. }
  75858. if (!location) {
  75859. location = this._haloCenter;
  75860. }
  75861. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  75862. // offset of the headset from the anchor.
  75863. if (this.webVRCamera.leftCamera) {
  75864. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  75865. this._workingVector.subtractInPlace(this.webVRCamera.position);
  75866. location.subtractToRef(this._workingVector, this._workingVector);
  75867. }
  75868. else {
  75869. this._workingVector.copyFrom(location);
  75870. }
  75871. // Add height to account for user's height offset
  75872. if (this.isInVRMode) {
  75873. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  75874. }
  75875. else {
  75876. this._workingVector.y += this._defaultHeight;
  75877. }
  75878. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  75879. // Create animation from the camera's position to the new location
  75880. this.currentVRCamera.animations = [];
  75881. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75882. var animationCameraTeleportationKeys = [{
  75883. frame: 0,
  75884. value: this.currentVRCamera.position
  75885. },
  75886. {
  75887. frame: 11,
  75888. value: this._workingVector
  75889. }
  75890. ];
  75891. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  75892. animationCameraTeleportation.setEasingFunction(this._circleEase);
  75893. this.currentVRCamera.animations.push(animationCameraTeleportation);
  75894. this._postProcessMove.animations = [];
  75895. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75896. var vignetteWeightKeys = [];
  75897. vignetteWeightKeys.push({
  75898. frame: 0,
  75899. value: 0
  75900. });
  75901. vignetteWeightKeys.push({
  75902. frame: 5,
  75903. value: 8
  75904. });
  75905. vignetteWeightKeys.push({
  75906. frame: 11,
  75907. value: 0
  75908. });
  75909. animationPP.setKeys(vignetteWeightKeys);
  75910. this._postProcessMove.animations.push(animationPP);
  75911. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75912. var vignetteStretchKeys = [];
  75913. vignetteStretchKeys.push({
  75914. frame: 0,
  75915. value: 0
  75916. });
  75917. vignetteStretchKeys.push({
  75918. frame: 5,
  75919. value: 10
  75920. });
  75921. vignetteStretchKeys.push({
  75922. frame: 11,
  75923. value: 0
  75924. });
  75925. animationPP2.setKeys(vignetteStretchKeys);
  75926. this._postProcessMove.animations.push(animationPP2);
  75927. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  75928. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  75929. this._webVRCamera.attachPostProcess(this._postProcessMove);
  75930. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  75931. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  75932. });
  75933. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  75934. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  75935. });
  75936. };
  75937. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  75938. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75939. return;
  75940. }
  75941. var ray;
  75942. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  75943. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  75944. }
  75945. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  75946. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  75947. }
  75948. else {
  75949. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  75950. }
  75951. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75952. // Moving the gazeTracker on the mesh face targetted
  75953. if (hit && hit.pickedPoint) {
  75954. if (this._displayGaze) {
  75955. var multiplier = 1;
  75956. this._gazeTracker.isVisible = true;
  75957. if (this._isActionableMesh) {
  75958. multiplier = 3;
  75959. }
  75960. this._gazeTracker.scaling.x = hit.distance * multiplier;
  75961. this._gazeTracker.scaling.y = hit.distance * multiplier;
  75962. this._gazeTracker.scaling.z = hit.distance * multiplier;
  75963. var pickNormal = hit.getNormal();
  75964. // To avoid z-fighting
  75965. var deltaFighting = 0.002;
  75966. if (pickNormal) {
  75967. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  75968. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  75969. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  75970. }
  75971. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  75972. if (this._gazeTracker.position.x < 0) {
  75973. this._gazeTracker.position.x += deltaFighting;
  75974. }
  75975. else {
  75976. this._gazeTracker.position.x -= deltaFighting;
  75977. }
  75978. if (this._gazeTracker.position.y < 0) {
  75979. this._gazeTracker.position.y += deltaFighting;
  75980. }
  75981. else {
  75982. this._gazeTracker.position.y -= deltaFighting;
  75983. }
  75984. if (this._gazeTracker.position.z < 0) {
  75985. this._gazeTracker.position.z += deltaFighting;
  75986. }
  75987. else {
  75988. this._gazeTracker.position.z -= deltaFighting;
  75989. }
  75990. }
  75991. // Changing the size of the laser pointer based on the distance from the targetted point
  75992. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  75993. this._rightLaserPointer.scaling.y = hit.distance;
  75994. this._rightLaserPointer.position.z = -hit.distance / 2;
  75995. }
  75996. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  75997. this._leftLaserPointer.scaling.y = hit.distance;
  75998. this._leftLaserPointer.position.z = -hit.distance / 2;
  75999. }
  76000. }
  76001. else {
  76002. this._gazeTracker.isVisible = false;
  76003. }
  76004. if (hit && hit.pickedMesh) {
  76005. this._currentHit = hit;
  76006. if (this._pointerDownOnMeshAsked) {
  76007. this._scene.simulatePointerMove(this._currentHit);
  76008. }
  76009. // The object selected is the floor, we're in a teleportation scenario
  76010. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76011. // Moving the teleportation area to this targetted point
  76012. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76013. if (this._currentMeshSelected &&
  76014. !this._isTeleportationFloor(this._currentMeshSelected)) {
  76015. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76016. }
  76017. this._currentMeshSelected = null;
  76018. this._moveTeleportationSelectorTo(hit);
  76019. return;
  76020. }
  76021. // If not, we're in a selection scenario
  76022. this._hideTeleportationTarget();
  76023. this._teleportationAllowed = false;
  76024. if (hit.pickedMesh !== this._currentMeshSelected) {
  76025. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76026. this.onNewMeshPicked.notifyObservers(hit);
  76027. this._currentMeshSelected = hit.pickedMesh;
  76028. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76029. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76030. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76031. this._isActionableMesh = true;
  76032. }
  76033. else {
  76034. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76035. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76036. this._isActionableMesh = false;
  76037. }
  76038. try {
  76039. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76040. }
  76041. catch (err) {
  76042. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76043. }
  76044. }
  76045. else {
  76046. if (this._currentMeshSelected) {
  76047. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76048. }
  76049. this._currentMeshSelected = null;
  76050. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76051. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76052. }
  76053. }
  76054. }
  76055. else {
  76056. this._currentHit = null;
  76057. this._currentMeshSelected = null;
  76058. this._teleportationAllowed = false;
  76059. this._hideTeleportationTarget();
  76060. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76061. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76062. }
  76063. };
  76064. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76065. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76066. this._leftLaserPointer.material.emissiveColor = color;
  76067. }
  76068. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76069. this._rightLaserPointer.material.emissiveColor = color;
  76070. }
  76071. };
  76072. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76073. if (this._gazeTracker.material) {
  76074. this._gazeTracker.material.emissiveColor = color;
  76075. }
  76076. };
  76077. VRExperienceHelper.prototype.dispose = function () {
  76078. if (this.isInVRMode) {
  76079. this.exitVR();
  76080. }
  76081. if (this._passProcessMove) {
  76082. this._passProcessMove.dispose();
  76083. }
  76084. if (this._postProcessMove) {
  76085. this._postProcessMove.dispose();
  76086. }
  76087. if (this._webVRCamera) {
  76088. this._webVRCamera.dispose();
  76089. }
  76090. if (this._vrDeviceOrientationCamera) {
  76091. this._vrDeviceOrientationCamera.dispose();
  76092. }
  76093. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76094. document.body.removeChild(this._btnVR);
  76095. }
  76096. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76097. this._deviceOrientationCamera.dispose();
  76098. }
  76099. if (this._gazeTracker) {
  76100. this._gazeTracker.dispose();
  76101. }
  76102. if (this._teleportationTarget) {
  76103. this._teleportationTarget.dispose();
  76104. }
  76105. this._floorMeshesCollection = [];
  76106. document.removeEventListener("keydown", this._onKeyDown);
  76107. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76108. window.removeEventListener("resize", this._onResize);
  76109. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76110. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76111. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76112. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76113. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76114. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76115. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76116. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76117. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76118. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76119. this._scene.unregisterBeforeRender(this.beforeRender);
  76120. };
  76121. VRExperienceHelper.prototype.getClassName = function () {
  76122. return "VRExperienceHelper";
  76123. };
  76124. return VRExperienceHelper;
  76125. }());
  76126. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76127. })(BABYLON || (BABYLON = {}));
  76128. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76129. // Mainly based on these 2 articles :
  76130. // 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
  76131. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76132. var BABYLON;
  76133. (function (BABYLON) {
  76134. var JoystickAxis;
  76135. (function (JoystickAxis) {
  76136. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76137. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76138. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76139. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76140. var VirtualJoystick = /** @class */ (function () {
  76141. function VirtualJoystick(leftJoystick) {
  76142. var _this = this;
  76143. if (leftJoystick) {
  76144. this._leftJoystick = true;
  76145. }
  76146. else {
  76147. this._leftJoystick = false;
  76148. }
  76149. VirtualJoystick._globalJoystickIndex++;
  76150. // By default left & right arrow keys are moving the X
  76151. // and up & down keys are moving the Y
  76152. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76153. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76154. this.reverseLeftRight = false;
  76155. this.reverseUpDown = false;
  76156. // collections of pointers
  76157. this._touches = new BABYLON.StringDictionary();
  76158. this.deltaPosition = BABYLON.Vector3.Zero();
  76159. this._joystickSensibility = 25;
  76160. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76161. this._onResize = function (evt) {
  76162. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76163. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76164. if (VirtualJoystick.vjCanvas) {
  76165. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76166. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76167. }
  76168. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76169. };
  76170. // injecting a canvas element on top of the canvas 3D game
  76171. if (!VirtualJoystick.vjCanvas) {
  76172. window.addEventListener("resize", this._onResize, false);
  76173. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76174. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76175. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76176. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76177. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76178. VirtualJoystick.vjCanvas.style.width = "100%";
  76179. VirtualJoystick.vjCanvas.style.height = "100%";
  76180. VirtualJoystick.vjCanvas.style.position = "absolute";
  76181. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76182. VirtualJoystick.vjCanvas.style.top = "0px";
  76183. VirtualJoystick.vjCanvas.style.left = "0px";
  76184. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76185. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76186. // Support for jQuery PEP polyfill
  76187. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76188. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76189. if (!context) {
  76190. throw new Error("Unable to create canvas for virtual joystick");
  76191. }
  76192. VirtualJoystick.vjCanvasContext = context;
  76193. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76194. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76195. document.body.appendChild(VirtualJoystick.vjCanvas);
  76196. }
  76197. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76198. this.pressed = false;
  76199. // default joystick color
  76200. this._joystickColor = "cyan";
  76201. this._joystickPointerID = -1;
  76202. // current joystick position
  76203. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76204. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76205. // origin joystick position
  76206. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76207. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76208. this._onPointerDownHandlerRef = function (evt) {
  76209. _this._onPointerDown(evt);
  76210. };
  76211. this._onPointerMoveHandlerRef = function (evt) {
  76212. _this._onPointerMove(evt);
  76213. };
  76214. this._onPointerUpHandlerRef = function (evt) {
  76215. _this._onPointerUp(evt);
  76216. };
  76217. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76218. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76219. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76220. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76221. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76222. evt.preventDefault(); // Disables system menu
  76223. }, false);
  76224. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76225. }
  76226. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76227. this._joystickSensibility = newJoystickSensibility;
  76228. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76229. };
  76230. VirtualJoystick.prototype._onPointerDown = function (e) {
  76231. var positionOnScreenCondition;
  76232. e.preventDefault();
  76233. if (this._leftJoystick === true) {
  76234. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76235. }
  76236. else {
  76237. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76238. }
  76239. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76240. // First contact will be dedicated to the virtual joystick
  76241. this._joystickPointerID = e.pointerId;
  76242. this._joystickPointerStartPos.x = e.clientX;
  76243. this._joystickPointerStartPos.y = e.clientY;
  76244. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76245. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76246. this._deltaJoystickVector.x = 0;
  76247. this._deltaJoystickVector.y = 0;
  76248. this.pressed = true;
  76249. this._touches.add(e.pointerId.toString(), e);
  76250. }
  76251. else {
  76252. // You can only trigger the action buttons with a joystick declared
  76253. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76254. this._action();
  76255. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76256. }
  76257. }
  76258. };
  76259. VirtualJoystick.prototype._onPointerMove = function (e) {
  76260. // If the current pointer is the one associated to the joystick (first touch contact)
  76261. if (this._joystickPointerID == e.pointerId) {
  76262. this._joystickPointerPos.x = e.clientX;
  76263. this._joystickPointerPos.y = e.clientY;
  76264. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76265. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76266. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76267. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76268. switch (this._axisTargetedByLeftAndRight) {
  76269. case JoystickAxis.X:
  76270. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76271. break;
  76272. case JoystickAxis.Y:
  76273. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76274. break;
  76275. case JoystickAxis.Z:
  76276. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76277. break;
  76278. }
  76279. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76280. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76281. switch (this._axisTargetedByUpAndDown) {
  76282. case JoystickAxis.X:
  76283. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76284. break;
  76285. case JoystickAxis.Y:
  76286. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76287. break;
  76288. case JoystickAxis.Z:
  76289. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  76290. break;
  76291. }
  76292. }
  76293. else {
  76294. var data = this._touches.get(e.pointerId.toString());
  76295. if (data) {
  76296. data.x = e.clientX;
  76297. data.y = e.clientY;
  76298. }
  76299. }
  76300. };
  76301. VirtualJoystick.prototype._onPointerUp = function (e) {
  76302. if (this._joystickPointerID == e.pointerId) {
  76303. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  76304. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  76305. this._joystickPointerID = -1;
  76306. this.pressed = false;
  76307. }
  76308. else {
  76309. var touch = this._touches.get(e.pointerId.toString());
  76310. if (touch) {
  76311. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76312. }
  76313. }
  76314. this._deltaJoystickVector.x = 0;
  76315. this._deltaJoystickVector.y = 0;
  76316. this._touches.remove(e.pointerId.toString());
  76317. };
  76318. /**
  76319. * Change the color of the virtual joystick
  76320. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  76321. */
  76322. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  76323. this._joystickColor = newColor;
  76324. };
  76325. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  76326. this._action = action;
  76327. };
  76328. // Define which axis you'd like to control for left & right
  76329. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  76330. switch (axis) {
  76331. case JoystickAxis.X:
  76332. case JoystickAxis.Y:
  76333. case JoystickAxis.Z:
  76334. this._axisTargetedByLeftAndRight = axis;
  76335. break;
  76336. default:
  76337. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76338. break;
  76339. }
  76340. };
  76341. // Define which axis you'd like to control for up & down
  76342. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  76343. switch (axis) {
  76344. case JoystickAxis.X:
  76345. case JoystickAxis.Y:
  76346. case JoystickAxis.Z:
  76347. this._axisTargetedByUpAndDown = axis;
  76348. break;
  76349. default:
  76350. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76351. break;
  76352. }
  76353. };
  76354. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  76355. var _this = this;
  76356. if (this.pressed) {
  76357. this._touches.forEach(function (key, touch) {
  76358. if (touch.pointerId === _this._joystickPointerID) {
  76359. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  76360. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  76361. VirtualJoystick.vjCanvasContext.beginPath();
  76362. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76363. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76364. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  76365. VirtualJoystick.vjCanvasContext.stroke();
  76366. VirtualJoystick.vjCanvasContext.closePath();
  76367. VirtualJoystick.vjCanvasContext.beginPath();
  76368. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76369. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76370. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  76371. VirtualJoystick.vjCanvasContext.stroke();
  76372. VirtualJoystick.vjCanvasContext.closePath();
  76373. VirtualJoystick.vjCanvasContext.beginPath();
  76374. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76375. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  76376. VirtualJoystick.vjCanvasContext.stroke();
  76377. VirtualJoystick.vjCanvasContext.closePath();
  76378. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  76379. }
  76380. else {
  76381. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76382. VirtualJoystick.vjCanvasContext.beginPath();
  76383. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  76384. VirtualJoystick.vjCanvasContext.beginPath();
  76385. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  76386. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76387. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  76388. VirtualJoystick.vjCanvasContext.stroke();
  76389. VirtualJoystick.vjCanvasContext.closePath();
  76390. touch.prevX = touch.x;
  76391. touch.prevY = touch.y;
  76392. }
  76393. ;
  76394. });
  76395. }
  76396. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76397. };
  76398. VirtualJoystick.prototype.releaseCanvas = function () {
  76399. if (VirtualJoystick.vjCanvas) {
  76400. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  76401. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  76402. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  76403. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  76404. window.removeEventListener("resize", this._onResize);
  76405. document.body.removeChild(VirtualJoystick.vjCanvas);
  76406. VirtualJoystick.vjCanvas = null;
  76407. }
  76408. };
  76409. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  76410. VirtualJoystick._globalJoystickIndex = 0;
  76411. return VirtualJoystick;
  76412. }());
  76413. BABYLON.VirtualJoystick = VirtualJoystick;
  76414. })(BABYLON || (BABYLON = {}));
  76415. //# sourceMappingURL=babylon.virtualJoystick.js.map
  76416. var BABYLON;
  76417. (function (BABYLON) {
  76418. // We're mainly based on the logic defined into the FreeCamera code
  76419. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  76420. __extends(VirtualJoysticksCamera, _super);
  76421. function VirtualJoysticksCamera(name, position, scene) {
  76422. var _this = _super.call(this, name, position, scene) || this;
  76423. _this.inputs.addVirtualJoystick();
  76424. return _this;
  76425. }
  76426. VirtualJoysticksCamera.prototype.getClassName = function () {
  76427. return "VirtualJoysticksCamera";
  76428. };
  76429. return VirtualJoysticksCamera;
  76430. }(BABYLON.FreeCamera));
  76431. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  76432. })(BABYLON || (BABYLON = {}));
  76433. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  76434. var BABYLON;
  76435. (function (BABYLON) {
  76436. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  76437. function FreeCameraVirtualJoystickInput() {
  76438. }
  76439. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  76440. return this._leftjoystick;
  76441. };
  76442. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  76443. return this._rightjoystick;
  76444. };
  76445. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  76446. if (this._leftjoystick) {
  76447. var camera = this.camera;
  76448. var speed = camera._computeLocalCameraSpeed() * 50;
  76449. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  76450. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  76451. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  76452. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  76453. if (!this._leftjoystick.pressed) {
  76454. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  76455. }
  76456. if (!this._rightjoystick.pressed) {
  76457. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  76458. }
  76459. }
  76460. };
  76461. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  76462. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  76463. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  76464. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  76465. this._leftjoystick.setJoystickSensibility(0.15);
  76466. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  76467. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  76468. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  76469. this._rightjoystick.reverseUpDown = true;
  76470. this._rightjoystick.setJoystickSensibility(0.05);
  76471. this._rightjoystick.setJoystickColor("yellow");
  76472. };
  76473. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  76474. this._leftjoystick.releaseCanvas();
  76475. this._rightjoystick.releaseCanvas();
  76476. };
  76477. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  76478. return "FreeCameraVirtualJoystickInput";
  76479. };
  76480. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  76481. return "virtualJoystick";
  76482. };
  76483. return FreeCameraVirtualJoystickInput;
  76484. }());
  76485. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  76486. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  76487. })(BABYLON || (BABYLON = {}));
  76488. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  76489. var BABYLON;
  76490. (function (BABYLON) {
  76491. var SimplificationSettings = /** @class */ (function () {
  76492. function SimplificationSettings(quality, distance, optimizeMesh) {
  76493. this.quality = quality;
  76494. this.distance = distance;
  76495. this.optimizeMesh = optimizeMesh;
  76496. }
  76497. return SimplificationSettings;
  76498. }());
  76499. BABYLON.SimplificationSettings = SimplificationSettings;
  76500. var SimplificationQueue = /** @class */ (function () {
  76501. function SimplificationQueue() {
  76502. this.running = false;
  76503. this._simplificationArray = [];
  76504. }
  76505. SimplificationQueue.prototype.addTask = function (task) {
  76506. this._simplificationArray.push(task);
  76507. };
  76508. SimplificationQueue.prototype.executeNext = function () {
  76509. var task = this._simplificationArray.pop();
  76510. if (task) {
  76511. this.running = true;
  76512. this.runSimplification(task);
  76513. }
  76514. else {
  76515. this.running = false;
  76516. }
  76517. };
  76518. SimplificationQueue.prototype.runSimplification = function (task) {
  76519. var _this = this;
  76520. if (task.parallelProcessing) {
  76521. //parallel simplifier
  76522. task.settings.forEach(function (setting) {
  76523. var simplifier = _this.getSimplifier(task);
  76524. simplifier.simplify(setting, function (newMesh) {
  76525. task.mesh.addLODLevel(setting.distance, newMesh);
  76526. newMesh.isVisible = true;
  76527. //check if it is the last
  76528. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  76529. //all done, run the success callback.
  76530. task.successCallback();
  76531. }
  76532. _this.executeNext();
  76533. });
  76534. });
  76535. }
  76536. else {
  76537. //single simplifier.
  76538. var simplifier = this.getSimplifier(task);
  76539. var runDecimation = function (setting, callback) {
  76540. simplifier.simplify(setting, function (newMesh) {
  76541. task.mesh.addLODLevel(setting.distance, newMesh);
  76542. newMesh.isVisible = true;
  76543. //run the next quality level
  76544. callback();
  76545. });
  76546. };
  76547. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  76548. runDecimation(task.settings[loop.index], function () {
  76549. loop.executeNext();
  76550. });
  76551. }, function () {
  76552. //execution ended, run the success callback.
  76553. if (task.successCallback) {
  76554. task.successCallback();
  76555. }
  76556. _this.executeNext();
  76557. });
  76558. }
  76559. };
  76560. SimplificationQueue.prototype.getSimplifier = function (task) {
  76561. switch (task.simplificationType) {
  76562. case SimplificationType.QUADRATIC:
  76563. default:
  76564. return new QuadraticErrorSimplification(task.mesh);
  76565. }
  76566. };
  76567. return SimplificationQueue;
  76568. }());
  76569. BABYLON.SimplificationQueue = SimplificationQueue;
  76570. /**
  76571. * The implemented types of simplification.
  76572. * At the moment only Quadratic Error Decimation is implemented.
  76573. */
  76574. var SimplificationType;
  76575. (function (SimplificationType) {
  76576. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  76577. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  76578. var DecimationTriangle = /** @class */ (function () {
  76579. function DecimationTriangle(vertices) {
  76580. this.vertices = vertices;
  76581. this.error = new Array(4);
  76582. this.deleted = false;
  76583. this.isDirty = false;
  76584. this.deletePending = false;
  76585. this.borderFactor = 0;
  76586. }
  76587. return DecimationTriangle;
  76588. }());
  76589. BABYLON.DecimationTriangle = DecimationTriangle;
  76590. var DecimationVertex = /** @class */ (function () {
  76591. function DecimationVertex(position, id) {
  76592. this.position = position;
  76593. this.id = id;
  76594. this.isBorder = true;
  76595. this.q = new QuadraticMatrix();
  76596. this.triangleCount = 0;
  76597. this.triangleStart = 0;
  76598. this.originalOffsets = [];
  76599. }
  76600. DecimationVertex.prototype.updatePosition = function (newPosition) {
  76601. this.position.copyFrom(newPosition);
  76602. };
  76603. return DecimationVertex;
  76604. }());
  76605. BABYLON.DecimationVertex = DecimationVertex;
  76606. var QuadraticMatrix = /** @class */ (function () {
  76607. function QuadraticMatrix(data) {
  76608. this.data = new Array(10);
  76609. for (var i = 0; i < 10; ++i) {
  76610. if (data && data[i]) {
  76611. this.data[i] = data[i];
  76612. }
  76613. else {
  76614. this.data[i] = 0;
  76615. }
  76616. }
  76617. }
  76618. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  76619. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  76620. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  76621. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  76622. return det;
  76623. };
  76624. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  76625. for (var i = 0; i < 10; ++i) {
  76626. this.data[i] += matrix.data[i];
  76627. }
  76628. };
  76629. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  76630. for (var i = 0; i < 10; ++i) {
  76631. this.data[i] += data[i];
  76632. }
  76633. };
  76634. QuadraticMatrix.prototype.add = function (matrix) {
  76635. var m = new QuadraticMatrix();
  76636. for (var i = 0; i < 10; ++i) {
  76637. m.data[i] = this.data[i] + matrix.data[i];
  76638. }
  76639. return m;
  76640. };
  76641. QuadraticMatrix.FromData = function (a, b, c, d) {
  76642. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  76643. };
  76644. //returning an array to avoid garbage collection
  76645. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  76646. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  76647. };
  76648. return QuadraticMatrix;
  76649. }());
  76650. BABYLON.QuadraticMatrix = QuadraticMatrix;
  76651. var Reference = /** @class */ (function () {
  76652. function Reference(vertexId, triangleId) {
  76653. this.vertexId = vertexId;
  76654. this.triangleId = triangleId;
  76655. }
  76656. return Reference;
  76657. }());
  76658. BABYLON.Reference = Reference;
  76659. /**
  76660. * An implementation of the Quadratic Error simplification algorithm.
  76661. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  76662. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  76663. * @author RaananW
  76664. */
  76665. var QuadraticErrorSimplification = /** @class */ (function () {
  76666. function QuadraticErrorSimplification(_mesh) {
  76667. this._mesh = _mesh;
  76668. this.syncIterations = 5000;
  76669. this.aggressiveness = 7;
  76670. this.decimationIterations = 100;
  76671. this.boundingBoxEpsilon = BABYLON.Epsilon;
  76672. }
  76673. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  76674. var _this = this;
  76675. this.initDecimatedMesh();
  76676. //iterating through the submeshes array, one after the other.
  76677. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  76678. _this.initWithMesh(loop.index, function () {
  76679. _this.runDecimation(settings, loop.index, function () {
  76680. loop.executeNext();
  76681. });
  76682. }, settings.optimizeMesh);
  76683. }, function () {
  76684. setTimeout(function () {
  76685. successCallback(_this._reconstructedMesh);
  76686. }, 0);
  76687. });
  76688. };
  76689. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  76690. var _this = this;
  76691. var targetCount = ~~(this.triangles.length * settings.quality);
  76692. var deletedTriangles = 0;
  76693. var triangleCount = this.triangles.length;
  76694. var iterationFunction = function (iteration, callback) {
  76695. setTimeout(function () {
  76696. if (iteration % 5 === 0) {
  76697. _this.updateMesh(iteration === 0);
  76698. }
  76699. for (var i = 0; i < _this.triangles.length; ++i) {
  76700. _this.triangles[i].isDirty = false;
  76701. }
  76702. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  76703. var trianglesIterator = function (i) {
  76704. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  76705. var t = _this.triangles[tIdx];
  76706. if (!t)
  76707. return;
  76708. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  76709. return;
  76710. }
  76711. for (var j = 0; j < 3; ++j) {
  76712. if (t.error[j] < threshold) {
  76713. var deleted0 = [];
  76714. var deleted1 = [];
  76715. var v0 = t.vertices[j];
  76716. var v1 = t.vertices[(j + 1) % 3];
  76717. if (v0.isBorder || v1.isBorder)
  76718. continue;
  76719. var p = BABYLON.Vector3.Zero();
  76720. var n = BABYLON.Vector3.Zero();
  76721. var uv = BABYLON.Vector2.Zero();
  76722. var color = new BABYLON.Color4(0, 0, 0, 1);
  76723. _this.calculateError(v0, v1, p, n, uv, color);
  76724. var delTr = new Array();
  76725. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  76726. continue;
  76727. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  76728. continue;
  76729. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  76730. continue;
  76731. var uniqueArray = new Array();
  76732. delTr.forEach(function (deletedT) {
  76733. if (uniqueArray.indexOf(deletedT) === -1) {
  76734. deletedT.deletePending = true;
  76735. uniqueArray.push(deletedT);
  76736. }
  76737. });
  76738. if (uniqueArray.length % 2 !== 0) {
  76739. continue;
  76740. }
  76741. v0.q = v1.q.add(v0.q);
  76742. v0.updatePosition(p);
  76743. var tStart = _this.references.length;
  76744. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  76745. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  76746. var tCount = _this.references.length - tStart;
  76747. if (tCount <= v0.triangleCount) {
  76748. if (tCount) {
  76749. for (var c = 0; c < tCount; c++) {
  76750. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  76751. }
  76752. }
  76753. }
  76754. else {
  76755. v0.triangleStart = tStart;
  76756. }
  76757. v0.triangleCount = tCount;
  76758. break;
  76759. }
  76760. }
  76761. };
  76762. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  76763. }, 0);
  76764. };
  76765. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  76766. if (triangleCount - deletedTriangles <= targetCount)
  76767. loop.breakLoop();
  76768. else {
  76769. iterationFunction(loop.index, function () {
  76770. loop.executeNext();
  76771. });
  76772. }
  76773. }, function () {
  76774. setTimeout(function () {
  76775. //reconstruct this part of the mesh
  76776. _this.reconstructMesh(submeshIndex);
  76777. successCallback();
  76778. }, 0);
  76779. });
  76780. };
  76781. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  76782. var _this = this;
  76783. this.vertices = [];
  76784. this.triangles = [];
  76785. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76786. var indices = this._mesh.getIndices();
  76787. var submesh = this._mesh.subMeshes[submeshIndex];
  76788. var findInVertices = function (positionToSearch) {
  76789. if (optimizeMesh) {
  76790. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  76791. if (_this.vertices[ii].position.equals(positionToSearch)) {
  76792. return _this.vertices[ii];
  76793. }
  76794. }
  76795. }
  76796. return null;
  76797. };
  76798. var vertexReferences = [];
  76799. var vertexInit = function (i) {
  76800. if (!positionData) {
  76801. return;
  76802. }
  76803. var offset = i + submesh.verticesStart;
  76804. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  76805. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  76806. vertex.originalOffsets.push(offset);
  76807. if (vertex.id === _this.vertices.length) {
  76808. _this.vertices.push(vertex);
  76809. }
  76810. vertexReferences.push(vertex.id);
  76811. };
  76812. //var totalVertices = mesh.getTotalVertices();
  76813. var totalVertices = submesh.verticesCount;
  76814. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  76815. var indicesInit = function (i) {
  76816. if (!indices) {
  76817. return;
  76818. }
  76819. var offset = (submesh.indexStart / 3) + i;
  76820. var pos = (offset * 3);
  76821. var i0 = indices[pos + 0];
  76822. var i1 = indices[pos + 1];
  76823. var i2 = indices[pos + 2];
  76824. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  76825. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  76826. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  76827. var triangle = new DecimationTriangle([v0, v1, v2]);
  76828. triangle.originalOffset = pos;
  76829. _this.triangles.push(triangle);
  76830. };
  76831. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  76832. _this.init(callback);
  76833. });
  76834. });
  76835. };
  76836. QuadraticErrorSimplification.prototype.init = function (callback) {
  76837. var _this = this;
  76838. var triangleInit1 = function (i) {
  76839. var t = _this.triangles[i];
  76840. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  76841. for (var j = 0; j < 3; j++) {
  76842. 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))));
  76843. }
  76844. };
  76845. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  76846. var triangleInit2 = function (i) {
  76847. var t = _this.triangles[i];
  76848. for (var j = 0; j < 3; ++j) {
  76849. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  76850. }
  76851. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  76852. };
  76853. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  76854. callback();
  76855. });
  76856. });
  76857. };
  76858. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  76859. var newTriangles = [];
  76860. var i;
  76861. for (i = 0; i < this.vertices.length; ++i) {
  76862. this.vertices[i].triangleCount = 0;
  76863. }
  76864. var t;
  76865. var j;
  76866. for (i = 0; i < this.triangles.length; ++i) {
  76867. if (!this.triangles[i].deleted) {
  76868. t = this.triangles[i];
  76869. for (j = 0; j < 3; ++j) {
  76870. t.vertices[j].triangleCount = 1;
  76871. }
  76872. newTriangles.push(t);
  76873. }
  76874. }
  76875. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  76876. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  76877. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  76878. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  76879. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  76880. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76881. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  76882. var vertexCount = 0;
  76883. for (i = 0; i < this.vertices.length; ++i) {
  76884. var vertex = this.vertices[i];
  76885. vertex.id = vertexCount;
  76886. if (vertex.triangleCount) {
  76887. vertex.originalOffsets.forEach(function (originalOffset) {
  76888. if (!normalData) {
  76889. return;
  76890. }
  76891. newPositionData.push(vertex.position.x);
  76892. newPositionData.push(vertex.position.y);
  76893. newPositionData.push(vertex.position.z);
  76894. newNormalData.push(normalData[originalOffset * 3]);
  76895. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  76896. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  76897. if (uvs && uvs.length) {
  76898. newUVsData.push(uvs[(originalOffset * 2)]);
  76899. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  76900. }
  76901. else if (colorsData && colorsData.length) {
  76902. newColorsData.push(colorsData[(originalOffset * 4)]);
  76903. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  76904. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  76905. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  76906. }
  76907. ++vertexCount;
  76908. });
  76909. }
  76910. }
  76911. var startingIndex = this._reconstructedMesh.getTotalIndices();
  76912. var startingVertex = this._reconstructedMesh.getTotalVertices();
  76913. var submeshesArray = this._reconstructedMesh.subMeshes;
  76914. this._reconstructedMesh.subMeshes = [];
  76915. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  76916. var originalIndices = this._mesh.getIndices();
  76917. for (i = 0; i < newTriangles.length; ++i) {
  76918. t = newTriangles[i]; //now get the new referencing point for each vertex
  76919. [0, 1, 2].forEach(function (idx) {
  76920. var id = originalIndices[t.originalOffset + idx];
  76921. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  76922. if (offset < 0)
  76923. offset = 0;
  76924. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  76925. });
  76926. }
  76927. //overwriting the old vertex buffers and indices.
  76928. this._reconstructedMesh.setIndices(newIndicesArray);
  76929. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  76930. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  76931. if (newUVsData.length > 0)
  76932. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  76933. if (newColorsData.length > 0)
  76934. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  76935. //create submesh
  76936. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  76937. if (submeshIndex > 0) {
  76938. this._reconstructedMesh.subMeshes = [];
  76939. submeshesArray.forEach(function (submesh) {
  76940. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  76941. });
  76942. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  76943. }
  76944. };
  76945. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  76946. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  76947. this._reconstructedMesh.material = this._mesh.material;
  76948. this._reconstructedMesh.parent = this._mesh.parent;
  76949. this._reconstructedMesh.isVisible = false;
  76950. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  76951. };
  76952. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  76953. for (var i = 0; i < vertex1.triangleCount; ++i) {
  76954. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  76955. if (t.deleted)
  76956. continue;
  76957. var s = this.references[vertex1.triangleStart + i].vertexId;
  76958. var v1 = t.vertices[(s + 1) % 3];
  76959. var v2 = t.vertices[(s + 2) % 3];
  76960. if ((v1 === vertex2 || v2 === vertex2)) {
  76961. deletedArray[i] = true;
  76962. delTr.push(t);
  76963. continue;
  76964. }
  76965. var d1 = v1.position.subtract(point);
  76966. d1 = d1.normalize();
  76967. var d2 = v2.position.subtract(point);
  76968. d2 = d2.normalize();
  76969. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  76970. return true;
  76971. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  76972. deletedArray[i] = false;
  76973. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  76974. return true;
  76975. }
  76976. return false;
  76977. };
  76978. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  76979. var newDeleted = deletedTriangles;
  76980. for (var i = 0; i < vertex.triangleCount; ++i) {
  76981. var ref = this.references[vertex.triangleStart + i];
  76982. var t = this.triangles[ref.triangleId];
  76983. if (t.deleted)
  76984. continue;
  76985. if (deletedArray[i] && t.deletePending) {
  76986. t.deleted = true;
  76987. newDeleted++;
  76988. continue;
  76989. }
  76990. t.vertices[ref.vertexId] = origVertex;
  76991. t.isDirty = true;
  76992. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  76993. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  76994. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  76995. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  76996. this.references.push(ref);
  76997. }
  76998. return newDeleted;
  76999. };
  77000. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77001. for (var i = 0; i < this.vertices.length; ++i) {
  77002. var vCount = [];
  77003. var vId = [];
  77004. var v = this.vertices[i];
  77005. var j;
  77006. for (j = 0; j < v.triangleCount; ++j) {
  77007. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77008. for (var ii = 0; ii < 3; ii++) {
  77009. var ofs = 0;
  77010. var vv = triangle.vertices[ii];
  77011. while (ofs < vCount.length) {
  77012. if (vId[ofs] === vv.id)
  77013. break;
  77014. ++ofs;
  77015. }
  77016. if (ofs === vCount.length) {
  77017. vCount.push(1);
  77018. vId.push(vv.id);
  77019. }
  77020. else {
  77021. vCount[ofs]++;
  77022. }
  77023. }
  77024. }
  77025. for (j = 0; j < vCount.length; ++j) {
  77026. if (vCount[j] === 1) {
  77027. this.vertices[vId[j]].isBorder = true;
  77028. }
  77029. else {
  77030. this.vertices[vId[j]].isBorder = false;
  77031. }
  77032. }
  77033. }
  77034. };
  77035. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77036. if (identifyBorders === void 0) { identifyBorders = false; }
  77037. var i;
  77038. if (!identifyBorders) {
  77039. var newTrianglesVector = [];
  77040. for (i = 0; i < this.triangles.length; ++i) {
  77041. if (!this.triangles[i].deleted) {
  77042. newTrianglesVector.push(this.triangles[i]);
  77043. }
  77044. }
  77045. this.triangles = newTrianglesVector;
  77046. }
  77047. for (i = 0; i < this.vertices.length; ++i) {
  77048. this.vertices[i].triangleCount = 0;
  77049. this.vertices[i].triangleStart = 0;
  77050. }
  77051. var t;
  77052. var j;
  77053. var v;
  77054. for (i = 0; i < this.triangles.length; ++i) {
  77055. t = this.triangles[i];
  77056. for (j = 0; j < 3; ++j) {
  77057. v = t.vertices[j];
  77058. v.triangleCount++;
  77059. }
  77060. }
  77061. var tStart = 0;
  77062. for (i = 0; i < this.vertices.length; ++i) {
  77063. this.vertices[i].triangleStart = tStart;
  77064. tStart += this.vertices[i].triangleCount;
  77065. this.vertices[i].triangleCount = 0;
  77066. }
  77067. var newReferences = new Array(this.triangles.length * 3);
  77068. for (i = 0; i < this.triangles.length; ++i) {
  77069. t = this.triangles[i];
  77070. for (j = 0; j < 3; ++j) {
  77071. v = t.vertices[j];
  77072. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77073. v.triangleCount++;
  77074. }
  77075. }
  77076. this.references = newReferences;
  77077. if (identifyBorders) {
  77078. this.identifyBorder();
  77079. }
  77080. };
  77081. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77082. var x = point.x;
  77083. var y = point.y;
  77084. var z = point.z;
  77085. 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
  77086. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77087. };
  77088. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77089. var q = vertex1.q.add(vertex2.q);
  77090. var border = vertex1.isBorder && vertex2.isBorder;
  77091. var error = 0;
  77092. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77093. if (qDet !== 0 && !border) {
  77094. if (!pointResult) {
  77095. pointResult = BABYLON.Vector3.Zero();
  77096. }
  77097. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77098. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77099. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77100. error = this.vertexError(q, pointResult);
  77101. }
  77102. else {
  77103. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77104. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77105. var error1 = this.vertexError(q, vertex1.position);
  77106. var error2 = this.vertexError(q, vertex2.position);
  77107. var error3 = this.vertexError(q, p3);
  77108. error = Math.min(error1, error2, error3);
  77109. if (error === error1) {
  77110. if (pointResult) {
  77111. pointResult.copyFrom(vertex1.position);
  77112. }
  77113. }
  77114. else if (error === error2) {
  77115. if (pointResult) {
  77116. pointResult.copyFrom(vertex2.position);
  77117. }
  77118. }
  77119. else {
  77120. if (pointResult) {
  77121. pointResult.copyFrom(p3);
  77122. }
  77123. }
  77124. }
  77125. return error;
  77126. };
  77127. return QuadraticErrorSimplification;
  77128. }());
  77129. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77130. })(BABYLON || (BABYLON = {}));
  77131. //# sourceMappingURL=babylon.meshSimplification.js.map
  77132. var BABYLON;
  77133. (function (BABYLON) {
  77134. var MeshLODLevel = /** @class */ (function () {
  77135. function MeshLODLevel(distance, mesh) {
  77136. this.distance = distance;
  77137. this.mesh = mesh;
  77138. }
  77139. return MeshLODLevel;
  77140. }());
  77141. BABYLON.MeshLODLevel = MeshLODLevel;
  77142. })(BABYLON || (BABYLON = {}));
  77143. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77144. var BABYLON;
  77145. (function (BABYLON) {
  77146. /**
  77147. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77148. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77149. */
  77150. var SceneOptimization = /** @class */ (function () {
  77151. /**
  77152. * Creates the SceneOptimization object
  77153. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77154. * @param desc defines the description associated with the optimization
  77155. */
  77156. function SceneOptimization(
  77157. /**
  77158. * Defines the priority of this optimization (0 by default which means first in the list)
  77159. */
  77160. priority) {
  77161. if (priority === void 0) { priority = 0; }
  77162. this.priority = priority;
  77163. }
  77164. /**
  77165. * Gets a string describing the action executed by the current optimization
  77166. * @returns description string
  77167. */
  77168. SceneOptimization.prototype.getDescription = function () {
  77169. return "";
  77170. };
  77171. /**
  77172. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77173. * @param scene defines the current scene where to apply this optimization
  77174. * @param optimizer defines the current optimizer
  77175. * @returns true if everything that can be done was applied
  77176. */
  77177. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77178. return true;
  77179. };
  77180. ;
  77181. return SceneOptimization;
  77182. }());
  77183. BABYLON.SceneOptimization = SceneOptimization;
  77184. /**
  77185. * Defines an optimization used to reduce the size of render target textures
  77186. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77187. */
  77188. var TextureOptimization = /** @class */ (function (_super) {
  77189. __extends(TextureOptimization, _super);
  77190. /**
  77191. * Creates the TextureOptimization object
  77192. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77193. * @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
  77194. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77195. */
  77196. function TextureOptimization(
  77197. /**
  77198. * Defines the priority of this optimization (0 by default which means first in the list)
  77199. */
  77200. priority,
  77201. /**
  77202. * 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
  77203. */
  77204. maximumSize,
  77205. /**
  77206. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77207. */
  77208. step) {
  77209. if (priority === void 0) { priority = 0; }
  77210. if (maximumSize === void 0) { maximumSize = 1024; }
  77211. if (step === void 0) { step = 0.5; }
  77212. var _this = _super.call(this, priority) || this;
  77213. _this.priority = priority;
  77214. _this.maximumSize = maximumSize;
  77215. _this.step = step;
  77216. return _this;
  77217. }
  77218. /**
  77219. * Gets a string describing the action executed by the current optimization
  77220. * @returns description string
  77221. */
  77222. TextureOptimization.prototype.getDescription = function () {
  77223. return "Reducing render target texture size to " + this.maximumSize;
  77224. };
  77225. /**
  77226. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77227. * @param scene defines the current scene where to apply this optimization
  77228. * @param optimizer defines the current optimizer
  77229. * @returns true if everything that can be done was applied
  77230. */
  77231. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77232. var allDone = true;
  77233. for (var index = 0; index < scene.textures.length; index++) {
  77234. var texture = scene.textures[index];
  77235. if (!texture.canRescale || texture.getContext) {
  77236. continue;
  77237. }
  77238. var currentSize = texture.getSize();
  77239. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77240. if (maxDimension > this.maximumSize) {
  77241. texture.scale(this.step);
  77242. allDone = false;
  77243. }
  77244. }
  77245. return allDone;
  77246. };
  77247. return TextureOptimization;
  77248. }(SceneOptimization));
  77249. BABYLON.TextureOptimization = TextureOptimization;
  77250. /**
  77251. * Defines an optimization used to increase or decrease the rendering resolution
  77252. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77253. */
  77254. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77255. __extends(HardwareScalingOptimization, _super);
  77256. /**
  77257. * Creates the HardwareScalingOptimization object
  77258. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77259. * @param maximumScale defines the maximum scale to use (2 by default)
  77260. * @param step defines the step to use between two passes (0.5 by default)
  77261. */
  77262. function HardwareScalingOptimization(
  77263. /**
  77264. * Defines the priority of this optimization (0 by default which means first in the list)
  77265. */
  77266. priority,
  77267. /**
  77268. * Defines the maximum scale to use (2 by default)
  77269. */
  77270. maximumScale,
  77271. /**
  77272. * Defines the step to use between two passes (0.5 by default)
  77273. */
  77274. step) {
  77275. if (priority === void 0) { priority = 0; }
  77276. if (maximumScale === void 0) { maximumScale = 2; }
  77277. if (step === void 0) { step = 0.25; }
  77278. var _this = _super.call(this, priority) || this;
  77279. _this.priority = priority;
  77280. _this.maximumScale = maximumScale;
  77281. _this.step = step;
  77282. _this._currentScale = -1;
  77283. _this._directionOffset = 1;
  77284. return _this;
  77285. }
  77286. /**
  77287. * Gets a string describing the action executed by the current optimization
  77288. * @return description string
  77289. */
  77290. HardwareScalingOptimization.prototype.getDescription = function () {
  77291. return "Setting hardware scaling level to " + this._currentScale;
  77292. };
  77293. /**
  77294. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77295. * @param scene defines the current scene where to apply this optimization
  77296. * @param optimizer defines the current optimizer
  77297. * @returns true if everything that can be done was applied
  77298. */
  77299. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  77300. if (this._currentScale === -1) {
  77301. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  77302. if (this._currentScale > this.maximumScale) {
  77303. this._directionOffset = -1;
  77304. }
  77305. }
  77306. this._currentScale += this._directionOffset * this.step;
  77307. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  77308. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  77309. };
  77310. ;
  77311. return HardwareScalingOptimization;
  77312. }(SceneOptimization));
  77313. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  77314. /**
  77315. * Defines an optimization used to remove shadows
  77316. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77317. */
  77318. var ShadowsOptimization = /** @class */ (function (_super) {
  77319. __extends(ShadowsOptimization, _super);
  77320. function ShadowsOptimization() {
  77321. return _super !== null && _super.apply(this, arguments) || this;
  77322. }
  77323. /**
  77324. * Gets a string describing the action executed by the current optimization
  77325. * @return description string
  77326. */
  77327. ShadowsOptimization.prototype.getDescription = function () {
  77328. return "Turning shadows on/off";
  77329. };
  77330. /**
  77331. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77332. * @param scene defines the current scene where to apply this optimization
  77333. * @param optimizer defines the current optimizer
  77334. * @returns true if everything that can be done was applied
  77335. */
  77336. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  77337. scene.shadowsEnabled = optimizer.isInImprovementMode;
  77338. return true;
  77339. };
  77340. ;
  77341. return ShadowsOptimization;
  77342. }(SceneOptimization));
  77343. BABYLON.ShadowsOptimization = ShadowsOptimization;
  77344. /**
  77345. * Defines an optimization used to turn post-processes off
  77346. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77347. */
  77348. var PostProcessesOptimization = /** @class */ (function (_super) {
  77349. __extends(PostProcessesOptimization, _super);
  77350. function PostProcessesOptimization() {
  77351. return _super !== null && _super.apply(this, arguments) || this;
  77352. }
  77353. /**
  77354. * Gets a string describing the action executed by the current optimization
  77355. * @return description string
  77356. */
  77357. PostProcessesOptimization.prototype.getDescription = function () {
  77358. return "Turning post-processes on/off";
  77359. };
  77360. /**
  77361. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77362. * @param scene defines the current scene where to apply this optimization
  77363. * @param optimizer defines the current optimizer
  77364. * @returns true if everything that can be done was applied
  77365. */
  77366. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  77367. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  77368. return true;
  77369. };
  77370. ;
  77371. return PostProcessesOptimization;
  77372. }(SceneOptimization));
  77373. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  77374. /**
  77375. * Defines an optimization used to turn lens flares off
  77376. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77377. */
  77378. var LensFlaresOptimization = /** @class */ (function (_super) {
  77379. __extends(LensFlaresOptimization, _super);
  77380. function LensFlaresOptimization() {
  77381. return _super !== null && _super.apply(this, arguments) || this;
  77382. }
  77383. /**
  77384. * Gets a string describing the action executed by the current optimization
  77385. * @return description string
  77386. */
  77387. LensFlaresOptimization.prototype.getDescription = function () {
  77388. return "Turning lens flares on/off";
  77389. };
  77390. /**
  77391. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77392. * @param scene defines the current scene where to apply this optimization
  77393. * @param optimizer defines the current optimizer
  77394. * @returns true if everything that can be done was applied
  77395. */
  77396. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  77397. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  77398. return true;
  77399. };
  77400. ;
  77401. return LensFlaresOptimization;
  77402. }(SceneOptimization));
  77403. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  77404. /**
  77405. * Defines an optimization based on user defined callback.
  77406. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77407. */
  77408. var CustomOptimization = /** @class */ (function (_super) {
  77409. __extends(CustomOptimization, _super);
  77410. function CustomOptimization() {
  77411. return _super !== null && _super.apply(this, arguments) || this;
  77412. }
  77413. /**
  77414. * Gets a string describing the action executed by the current optimization
  77415. * @returns description string
  77416. */
  77417. CustomOptimization.prototype.getDescription = function () {
  77418. if (this.onGetDescription) {
  77419. return this.onGetDescription();
  77420. }
  77421. return "Running user defined callback";
  77422. };
  77423. /**
  77424. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77425. * @param scene defines the current scene where to apply this optimization
  77426. * @param optimizer defines the current optimizer
  77427. * @returns true if everything that can be done was applied
  77428. */
  77429. CustomOptimization.prototype.apply = function (scene, optimizer) {
  77430. if (this.onApply) {
  77431. return this.onApply(scene, optimizer);
  77432. }
  77433. return true;
  77434. };
  77435. ;
  77436. return CustomOptimization;
  77437. }(SceneOptimization));
  77438. BABYLON.CustomOptimization = CustomOptimization;
  77439. /**
  77440. * Defines an optimization used to turn particles off
  77441. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77442. */
  77443. var ParticlesOptimization = /** @class */ (function (_super) {
  77444. __extends(ParticlesOptimization, _super);
  77445. function ParticlesOptimization() {
  77446. return _super !== null && _super.apply(this, arguments) || this;
  77447. }
  77448. /**
  77449. * Gets a string describing the action executed by the current optimization
  77450. * @return description string
  77451. */
  77452. ParticlesOptimization.prototype.getDescription = function () {
  77453. return "Turning particles on/off";
  77454. };
  77455. /**
  77456. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77457. * @param scene defines the current scene where to apply this optimization
  77458. * @param optimizer defines the current optimizer
  77459. * @returns true if everything that can be done was applied
  77460. */
  77461. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  77462. scene.particlesEnabled = optimizer.isInImprovementMode;
  77463. return true;
  77464. };
  77465. ;
  77466. return ParticlesOptimization;
  77467. }(SceneOptimization));
  77468. BABYLON.ParticlesOptimization = ParticlesOptimization;
  77469. /**
  77470. * Defines an optimization used to turn render targets off
  77471. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77472. */
  77473. var RenderTargetsOptimization = /** @class */ (function (_super) {
  77474. __extends(RenderTargetsOptimization, _super);
  77475. function RenderTargetsOptimization() {
  77476. return _super !== null && _super.apply(this, arguments) || this;
  77477. }
  77478. /**
  77479. * Gets a string describing the action executed by the current optimization
  77480. * @return description string
  77481. */
  77482. RenderTargetsOptimization.prototype.getDescription = function () {
  77483. return "Turning render targets off";
  77484. };
  77485. /**
  77486. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77487. * @param scene defines the current scene where to apply this optimization
  77488. * @param optimizer defines the current optimizer
  77489. * @returns true if everything that can be done was applied
  77490. */
  77491. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  77492. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  77493. return true;
  77494. };
  77495. ;
  77496. return RenderTargetsOptimization;
  77497. }(SceneOptimization));
  77498. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  77499. /**
  77500. * Defines an optimization used to merge meshes with compatible materials
  77501. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77502. */
  77503. var MergeMeshesOptimization = /** @class */ (function (_super) {
  77504. __extends(MergeMeshesOptimization, _super);
  77505. function MergeMeshesOptimization() {
  77506. var _this = _super !== null && _super.apply(this, arguments) || this;
  77507. _this._canBeMerged = function (abstractMesh) {
  77508. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  77509. return false;
  77510. }
  77511. var mesh = abstractMesh;
  77512. if (!mesh.isVisible || !mesh.isEnabled()) {
  77513. return false;
  77514. }
  77515. if (mesh.instances.length > 0) {
  77516. return false;
  77517. }
  77518. if (mesh.skeleton || mesh.hasLODLevels) {
  77519. return false;
  77520. }
  77521. if (mesh.parent) {
  77522. return false;
  77523. }
  77524. return true;
  77525. };
  77526. return _this;
  77527. }
  77528. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  77529. /**
  77530. * Gets or sets a boolean which defines if optimization octree has to be updated
  77531. */
  77532. get: function () {
  77533. return MergeMeshesOptimization._UpdateSelectionTree;
  77534. },
  77535. /**
  77536. * Gets or sets a boolean which defines if optimization octree has to be updated
  77537. */
  77538. set: function (value) {
  77539. MergeMeshesOptimization._UpdateSelectionTree = value;
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. /**
  77545. * Gets a string describing the action executed by the current optimization
  77546. * @return description string
  77547. */
  77548. MergeMeshesOptimization.prototype.getDescription = function () {
  77549. return "Merging similar meshes together";
  77550. };
  77551. /**
  77552. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77553. * @param scene defines the current scene where to apply this optimization
  77554. * @param optimizer defines the current optimizer
  77555. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  77556. * @returns true if everything that can be done was applied
  77557. */
  77558. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  77559. var globalPool = scene.meshes.slice(0);
  77560. var globalLength = globalPool.length;
  77561. for (var index = 0; index < globalLength; index++) {
  77562. var currentPool = new Array();
  77563. var current = globalPool[index];
  77564. // Checks
  77565. if (!this._canBeMerged(current)) {
  77566. continue;
  77567. }
  77568. currentPool.push(current);
  77569. // Find compatible meshes
  77570. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  77571. var otherMesh = globalPool[subIndex];
  77572. if (!this._canBeMerged(otherMesh)) {
  77573. continue;
  77574. }
  77575. if (otherMesh.material !== current.material) {
  77576. continue;
  77577. }
  77578. if (otherMesh.checkCollisions !== current.checkCollisions) {
  77579. continue;
  77580. }
  77581. currentPool.push(otherMesh);
  77582. globalLength--;
  77583. globalPool.splice(subIndex, 1);
  77584. subIndex--;
  77585. }
  77586. if (currentPool.length < 2) {
  77587. continue;
  77588. }
  77589. // Merge meshes
  77590. BABYLON.Mesh.MergeMeshes(currentPool);
  77591. }
  77592. if (updateSelectionTree != undefined) {
  77593. if (updateSelectionTree) {
  77594. scene.createOrUpdateSelectionOctree();
  77595. }
  77596. }
  77597. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  77598. scene.createOrUpdateSelectionOctree();
  77599. }
  77600. return true;
  77601. };
  77602. ;
  77603. MergeMeshesOptimization._UpdateSelectionTree = false;
  77604. return MergeMeshesOptimization;
  77605. }(SceneOptimization));
  77606. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  77607. /**
  77608. * Defines a list of options used by SceneOptimizer
  77609. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77610. */
  77611. var SceneOptimizerOptions = /** @class */ (function () {
  77612. /**
  77613. * Creates a new list of options used by SceneOptimizer
  77614. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  77615. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  77616. */
  77617. function SceneOptimizerOptions(
  77618. /**
  77619. * Defines the target frame rate to reach (60 by default)
  77620. */
  77621. targetFrameRate,
  77622. /**
  77623. * Defines the interval between two checkes (2000ms by default)
  77624. */
  77625. trackerDuration) {
  77626. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  77627. if (trackerDuration === void 0) { trackerDuration = 2000; }
  77628. this.targetFrameRate = targetFrameRate;
  77629. this.trackerDuration = trackerDuration;
  77630. /**
  77631. * Gets the list of optimizations to apply
  77632. */
  77633. this.optimizations = new Array();
  77634. }
  77635. /**
  77636. * Add a new optimization
  77637. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  77638. * @returns the current SceneOptimizerOptions
  77639. */
  77640. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  77641. this.optimizations.push(optimization);
  77642. return this;
  77643. };
  77644. /**
  77645. * Add a new custom optimization
  77646. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  77647. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  77648. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77649. * @returns the current SceneOptimizerOptions
  77650. */
  77651. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  77652. if (priority === void 0) { priority = 0; }
  77653. var optimization = new CustomOptimization(priority);
  77654. optimization.onApply = onApply;
  77655. optimization.onGetDescription = onGetDescription;
  77656. this.optimizations.push(optimization);
  77657. return this;
  77658. };
  77659. /**
  77660. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  77661. * @param targetFrameRate defines the target frame rate (60 by default)
  77662. * @returns a SceneOptimizerOptions object
  77663. */
  77664. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  77665. var result = new SceneOptimizerOptions(targetFrameRate);
  77666. var priority = 0;
  77667. result.addOptimization(new MergeMeshesOptimization(priority));
  77668. result.addOptimization(new ShadowsOptimization(priority));
  77669. result.addOptimization(new LensFlaresOptimization(priority));
  77670. // Next priority
  77671. priority++;
  77672. result.addOptimization(new PostProcessesOptimization(priority));
  77673. result.addOptimization(new ParticlesOptimization(priority));
  77674. // Next priority
  77675. priority++;
  77676. result.addOptimization(new TextureOptimization(priority, 1024));
  77677. return result;
  77678. };
  77679. /**
  77680. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  77681. * @param targetFrameRate defines the target frame rate (60 by default)
  77682. * @returns a SceneOptimizerOptions object
  77683. */
  77684. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  77685. var result = new SceneOptimizerOptions(targetFrameRate);
  77686. var priority = 0;
  77687. result.addOptimization(new MergeMeshesOptimization(priority));
  77688. result.addOptimization(new ShadowsOptimization(priority));
  77689. result.addOptimization(new LensFlaresOptimization(priority));
  77690. // Next priority
  77691. priority++;
  77692. result.addOptimization(new PostProcessesOptimization(priority));
  77693. result.addOptimization(new ParticlesOptimization(priority));
  77694. // Next priority
  77695. priority++;
  77696. result.addOptimization(new TextureOptimization(priority, 512));
  77697. // Next priority
  77698. priority++;
  77699. result.addOptimization(new RenderTargetsOptimization(priority));
  77700. // Next priority
  77701. priority++;
  77702. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  77703. return result;
  77704. };
  77705. /**
  77706. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  77707. * @param targetFrameRate defines the target frame rate (60 by default)
  77708. * @returns a SceneOptimizerOptions object
  77709. */
  77710. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  77711. var result = new SceneOptimizerOptions(targetFrameRate);
  77712. var priority = 0;
  77713. result.addOptimization(new MergeMeshesOptimization(priority));
  77714. result.addOptimization(new ShadowsOptimization(priority));
  77715. result.addOptimization(new LensFlaresOptimization(priority));
  77716. // Next priority
  77717. priority++;
  77718. result.addOptimization(new PostProcessesOptimization(priority));
  77719. result.addOptimization(new ParticlesOptimization(priority));
  77720. // Next priority
  77721. priority++;
  77722. result.addOptimization(new TextureOptimization(priority, 256));
  77723. // Next priority
  77724. priority++;
  77725. result.addOptimization(new RenderTargetsOptimization(priority));
  77726. // Next priority
  77727. priority++;
  77728. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  77729. return result;
  77730. };
  77731. return SceneOptimizerOptions;
  77732. }());
  77733. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  77734. /**
  77735. * Class used to run optimizations in order to reach a target frame rate
  77736. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77737. */
  77738. var SceneOptimizer = /** @class */ (function () {
  77739. /**
  77740. * Creates a new SceneOptimizer
  77741. * @param scene defines the scene to work on
  77742. * @param options defines the options to use with the SceneOptimizer
  77743. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  77744. * @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)
  77745. */
  77746. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  77747. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  77748. if (improvementMode === void 0) { improvementMode = false; }
  77749. var _this = this;
  77750. this._isRunning = false;
  77751. this._currentPriorityLevel = 0;
  77752. this._targetFrameRate = 60;
  77753. this._trackerDuration = 2000;
  77754. this._currentFrameRate = 0;
  77755. this._improvementMode = false;
  77756. /**
  77757. * Defines an observable called when the optimizer reaches the target frame rate
  77758. */
  77759. this.onSuccessObservable = new BABYLON.Observable();
  77760. /**
  77761. * Defines an observable called when the optimizer enables an optimization
  77762. */
  77763. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  77764. /**
  77765. * Defines an observable called when the optimizer is not able to reach the target frame rate
  77766. */
  77767. this.onFailureObservable = new BABYLON.Observable();
  77768. if (!options) {
  77769. this._options = new SceneOptimizerOptions();
  77770. }
  77771. else {
  77772. this._options = options;
  77773. }
  77774. if (this._options.targetFrameRate) {
  77775. this._targetFrameRate = this._options.targetFrameRate;
  77776. }
  77777. if (this._options.trackerDuration) {
  77778. this._trackerDuration = this._options.trackerDuration;
  77779. }
  77780. if (autoGeneratePriorities) {
  77781. var priority = 0;
  77782. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  77783. var optim = _a[_i];
  77784. optim.priority = priority++;
  77785. }
  77786. }
  77787. this._improvementMode = improvementMode;
  77788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77789. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  77790. _this._sceneDisposeObserver = null;
  77791. _this.dispose();
  77792. });
  77793. }
  77794. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  77795. /**
  77796. * Gets a boolean indicating if the optimizer is in improvement mode
  77797. */
  77798. get: function () {
  77799. return this._improvementMode;
  77800. },
  77801. enumerable: true,
  77802. configurable: true
  77803. });
  77804. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  77805. /**
  77806. * Gets the current priority level (0 at start)
  77807. */
  77808. get: function () {
  77809. return this._currentPriorityLevel;
  77810. },
  77811. enumerable: true,
  77812. configurable: true
  77813. });
  77814. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  77815. /**
  77816. * Gets the current frame rate checked by the SceneOptimizer
  77817. */
  77818. get: function () {
  77819. return this._currentFrameRate;
  77820. },
  77821. enumerable: true,
  77822. configurable: true
  77823. });
  77824. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  77825. /**
  77826. * Gets or sets the current target frame rate (60 by default)
  77827. */
  77828. get: function () {
  77829. return this._targetFrameRate;
  77830. },
  77831. /**
  77832. * Gets or sets the current target frame rate (60 by default)
  77833. */
  77834. set: function (value) {
  77835. this._targetFrameRate = value;
  77836. },
  77837. enumerable: true,
  77838. configurable: true
  77839. });
  77840. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  77841. /**
  77842. * Gets or sets the current interval between two checks (every 2000ms by default)
  77843. */
  77844. get: function () {
  77845. return this._trackerDuration;
  77846. },
  77847. /**
  77848. * Gets or sets the current interval between two checks (every 2000ms by default)
  77849. */
  77850. set: function (value) {
  77851. this._trackerDuration = value;
  77852. },
  77853. enumerable: true,
  77854. configurable: true
  77855. });
  77856. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  77857. /**
  77858. * Gets the list of active optimizations
  77859. */
  77860. get: function () {
  77861. return this._options.optimizations;
  77862. },
  77863. enumerable: true,
  77864. configurable: true
  77865. });
  77866. /**
  77867. * Stops the current optimizer
  77868. */
  77869. SceneOptimizer.prototype.stop = function () {
  77870. this._isRunning = false;
  77871. };
  77872. /**
  77873. * Reset the optimizer to initial step (current priority level = 0)
  77874. */
  77875. SceneOptimizer.prototype.reset = function () {
  77876. this._currentPriorityLevel = 0;
  77877. };
  77878. /**
  77879. * Start the optimizer. By default it will try to reach a specific framerate
  77880. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  77881. */
  77882. SceneOptimizer.prototype.start = function () {
  77883. var _this = this;
  77884. if (this._isRunning) {
  77885. return;
  77886. }
  77887. this._isRunning = true;
  77888. // Let's wait for the scene to be ready before running our check
  77889. this._scene.executeWhenReady(function () {
  77890. setTimeout(function () {
  77891. _this._checkCurrentState();
  77892. }, _this._trackerDuration);
  77893. });
  77894. };
  77895. SceneOptimizer.prototype._checkCurrentState = function () {
  77896. var _this = this;
  77897. if (!this._isRunning) {
  77898. return;
  77899. }
  77900. var scene = this._scene;
  77901. var options = this._options;
  77902. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  77903. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  77904. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  77905. this._isRunning = false;
  77906. this.onSuccessObservable.notifyObservers(this);
  77907. return;
  77908. }
  77909. // Apply current level of optimizations
  77910. var allDone = true;
  77911. var noOptimizationApplied = true;
  77912. for (var index = 0; index < options.optimizations.length; index++) {
  77913. var optimization = options.optimizations[index];
  77914. if (optimization.priority === this._currentPriorityLevel) {
  77915. noOptimizationApplied = false;
  77916. allDone = allDone && optimization.apply(scene, this);
  77917. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  77918. }
  77919. }
  77920. // If no optimization was applied, this is a failure :(
  77921. if (noOptimizationApplied) {
  77922. this._isRunning = false;
  77923. this.onFailureObservable.notifyObservers(this);
  77924. return;
  77925. }
  77926. // If all optimizations were done, move to next level
  77927. if (allDone) {
  77928. this._currentPriorityLevel++;
  77929. }
  77930. // Let's the system running for a specific amount of time before checking FPS
  77931. scene.executeWhenReady(function () {
  77932. setTimeout(function () {
  77933. _this._checkCurrentState();
  77934. }, _this._trackerDuration);
  77935. });
  77936. };
  77937. /**
  77938. * Release all resources
  77939. */
  77940. SceneOptimizer.prototype.dispose = function () {
  77941. this.stop();
  77942. this.onSuccessObservable.clear();
  77943. this.onFailureObservable.clear();
  77944. this.onNewOptimizationAppliedObservable.clear();
  77945. if (this._sceneDisposeObserver) {
  77946. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  77947. }
  77948. };
  77949. /**
  77950. * Helper function to create a SceneOptimizer with one single line of code
  77951. * @param scene defines the scene to work on
  77952. * @param options defines the options to use with the SceneOptimizer
  77953. * @param onSuccess defines a callback to call on success
  77954. * @param onFailure defines a callback to call on failure
  77955. * @returns the new SceneOptimizer object
  77956. */
  77957. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  77958. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  77959. if (onSuccess) {
  77960. optimizer.onSuccessObservable.add(function () {
  77961. onSuccess();
  77962. });
  77963. }
  77964. if (onFailure) {
  77965. optimizer.onFailureObservable.add(function () {
  77966. onFailure();
  77967. });
  77968. }
  77969. optimizer.start();
  77970. return optimizer;
  77971. };
  77972. return SceneOptimizer;
  77973. }());
  77974. BABYLON.SceneOptimizer = SceneOptimizer;
  77975. })(BABYLON || (BABYLON = {}));
  77976. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  77977. var BABYLON;
  77978. (function (BABYLON) {
  77979. var OutlineRenderer = /** @class */ (function () {
  77980. function OutlineRenderer(scene) {
  77981. this.zOffset = 1;
  77982. this._scene = scene;
  77983. }
  77984. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  77985. var _this = this;
  77986. if (useOverlay === void 0) { useOverlay = false; }
  77987. var scene = this._scene;
  77988. var engine = this._scene.getEngine();
  77989. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77990. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  77991. return;
  77992. }
  77993. var mesh = subMesh.getRenderingMesh();
  77994. var material = subMesh.getMaterial();
  77995. if (!material || !scene.activeCamera) {
  77996. return;
  77997. }
  77998. engine.enableEffect(this._effect);
  77999. // Logarithmic depth
  78000. if (material.useLogarithmicDepth) {
  78001. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78002. }
  78003. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78004. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78005. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78006. // Bones
  78007. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78008. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78009. }
  78010. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78011. // Alpha test
  78012. if (material && material.needAlphaTesting()) {
  78013. var alphaTexture = material.getAlphaTestTexture();
  78014. if (alphaTexture) {
  78015. this._effect.setTexture("diffuseSampler", alphaTexture);
  78016. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78017. }
  78018. }
  78019. engine.setZOffset(-this.zOffset);
  78020. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78021. engine.setZOffset(0);
  78022. };
  78023. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78024. var defines = [];
  78025. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78026. var mesh = subMesh.getMesh();
  78027. var material = subMesh.getMaterial();
  78028. if (material) {
  78029. // Alpha test
  78030. if (material.needAlphaTesting()) {
  78031. defines.push("#define ALPHATEST");
  78032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78033. attribs.push(BABYLON.VertexBuffer.UVKind);
  78034. defines.push("#define UV1");
  78035. }
  78036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78037. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78038. defines.push("#define UV2");
  78039. }
  78040. }
  78041. //Logarithmic depth
  78042. if (material.useLogarithmicDepth) {
  78043. defines.push("#define LOGARITHMICDEPTH");
  78044. }
  78045. }
  78046. // Bones
  78047. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78048. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78049. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78050. if (mesh.numBoneInfluencers > 4) {
  78051. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78052. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78053. }
  78054. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78055. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78056. }
  78057. else {
  78058. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78059. }
  78060. // Instances
  78061. if (useInstances) {
  78062. defines.push("#define INSTANCES");
  78063. attribs.push("world0");
  78064. attribs.push("world1");
  78065. attribs.push("world2");
  78066. attribs.push("world3");
  78067. }
  78068. // Get correct effect
  78069. var join = defines.join("\n");
  78070. if (this._cachedDefines !== join) {
  78071. this._cachedDefines = join;
  78072. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78073. }
  78074. return this._effect.isReady();
  78075. };
  78076. return OutlineRenderer;
  78077. }());
  78078. BABYLON.OutlineRenderer = OutlineRenderer;
  78079. })(BABYLON || (BABYLON = {}));
  78080. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78081. var BABYLON;
  78082. (function (BABYLON) {
  78083. var FaceAdjacencies = /** @class */ (function () {
  78084. function FaceAdjacencies() {
  78085. this.edges = new Array();
  78086. this.edgesConnectedCount = 0;
  78087. }
  78088. return FaceAdjacencies;
  78089. }());
  78090. var EdgesRenderer = /** @class */ (function () {
  78091. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78092. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78093. if (epsilon === void 0) { epsilon = 0.95; }
  78094. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78095. this.edgesWidthScalerForOrthographic = 1000.0;
  78096. this.edgesWidthScalerForPerspective = 50.0;
  78097. this._linesPositions = new Array();
  78098. this._linesNormals = new Array();
  78099. this._linesIndices = new Array();
  78100. this._buffers = {};
  78101. this._checkVerticesInsteadOfIndices = false;
  78102. this._source = source;
  78103. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78104. this._epsilon = epsilon;
  78105. this._prepareRessources();
  78106. this._generateEdgesLines();
  78107. }
  78108. EdgesRenderer.prototype._prepareRessources = function () {
  78109. if (this._lineShader) {
  78110. return;
  78111. }
  78112. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78113. attributes: ["position", "normal"],
  78114. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78115. });
  78116. this._lineShader.disableDepthWrite = true;
  78117. this._lineShader.backFaceCulling = false;
  78118. };
  78119. EdgesRenderer.prototype._rebuild = function () {
  78120. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78121. if (buffer) {
  78122. buffer._rebuild();
  78123. }
  78124. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78125. if (buffer) {
  78126. buffer._rebuild();
  78127. }
  78128. var scene = this._source.getScene();
  78129. var engine = scene.getEngine();
  78130. this._ib = engine.createIndexBuffer(this._linesIndices);
  78131. };
  78132. EdgesRenderer.prototype.dispose = function () {
  78133. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78134. if (buffer) {
  78135. buffer.dispose();
  78136. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78137. }
  78138. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78139. if (buffer) {
  78140. buffer.dispose();
  78141. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78142. }
  78143. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78144. this._lineShader.dispose();
  78145. };
  78146. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78147. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78148. return 0;
  78149. }
  78150. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78151. return 1;
  78152. }
  78153. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78154. return 2;
  78155. }
  78156. return -1;
  78157. };
  78158. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78159. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78160. return 0;
  78161. }
  78162. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78163. return 1;
  78164. }
  78165. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78166. return 2;
  78167. }
  78168. return -1;
  78169. };
  78170. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78171. var needToCreateLine;
  78172. if (edge === undefined) {
  78173. needToCreateLine = true;
  78174. }
  78175. else {
  78176. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78177. needToCreateLine = dotProduct < this._epsilon;
  78178. }
  78179. if (needToCreateLine) {
  78180. var offset = this._linesPositions.length / 3;
  78181. var normal = p0.subtract(p1);
  78182. normal.normalize();
  78183. // Positions
  78184. this._linesPositions.push(p0.x);
  78185. this._linesPositions.push(p0.y);
  78186. this._linesPositions.push(p0.z);
  78187. this._linesPositions.push(p0.x);
  78188. this._linesPositions.push(p0.y);
  78189. this._linesPositions.push(p0.z);
  78190. this._linesPositions.push(p1.x);
  78191. this._linesPositions.push(p1.y);
  78192. this._linesPositions.push(p1.z);
  78193. this._linesPositions.push(p1.x);
  78194. this._linesPositions.push(p1.y);
  78195. this._linesPositions.push(p1.z);
  78196. // Normals
  78197. this._linesNormals.push(p1.x);
  78198. this._linesNormals.push(p1.y);
  78199. this._linesNormals.push(p1.z);
  78200. this._linesNormals.push(-1);
  78201. this._linesNormals.push(p1.x);
  78202. this._linesNormals.push(p1.y);
  78203. this._linesNormals.push(p1.z);
  78204. this._linesNormals.push(1);
  78205. this._linesNormals.push(p0.x);
  78206. this._linesNormals.push(p0.y);
  78207. this._linesNormals.push(p0.z);
  78208. this._linesNormals.push(-1);
  78209. this._linesNormals.push(p0.x);
  78210. this._linesNormals.push(p0.y);
  78211. this._linesNormals.push(p0.z);
  78212. this._linesNormals.push(1);
  78213. // Indices
  78214. this._linesIndices.push(offset);
  78215. this._linesIndices.push(offset + 1);
  78216. this._linesIndices.push(offset + 2);
  78217. this._linesIndices.push(offset);
  78218. this._linesIndices.push(offset + 2);
  78219. this._linesIndices.push(offset + 3);
  78220. }
  78221. };
  78222. EdgesRenderer.prototype._generateEdgesLines = function () {
  78223. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78224. var indices = this._source.getIndices();
  78225. if (!indices || !positions) {
  78226. return;
  78227. }
  78228. // First let's find adjacencies
  78229. var adjacencies = new Array();
  78230. var faceNormals = new Array();
  78231. var index;
  78232. var faceAdjacencies;
  78233. // Prepare faces
  78234. for (index = 0; index < indices.length; index += 3) {
  78235. faceAdjacencies = new FaceAdjacencies();
  78236. var p0Index = indices[index];
  78237. var p1Index = indices[index + 1];
  78238. var p2Index = indices[index + 2];
  78239. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78240. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78241. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78242. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78243. faceNormal.normalize();
  78244. faceNormals.push(faceNormal);
  78245. adjacencies.push(faceAdjacencies);
  78246. }
  78247. // Scan
  78248. for (index = 0; index < adjacencies.length; index++) {
  78249. faceAdjacencies = adjacencies[index];
  78250. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78251. var otherFaceAdjacencies = adjacencies[otherIndex];
  78252. if (faceAdjacencies.edgesConnectedCount === 3) {
  78253. break;
  78254. }
  78255. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78256. continue;
  78257. }
  78258. var otherP0 = indices[otherIndex * 3];
  78259. var otherP1 = indices[otherIndex * 3 + 1];
  78260. var otherP2 = indices[otherIndex * 3 + 2];
  78261. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78262. var otherEdgeIndex = 0;
  78263. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78264. continue;
  78265. }
  78266. switch (edgeIndex) {
  78267. case 0:
  78268. if (this._checkVerticesInsteadOfIndices) {
  78269. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78270. }
  78271. else {
  78272. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78273. }
  78274. break;
  78275. case 1:
  78276. if (this._checkVerticesInsteadOfIndices) {
  78277. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78278. }
  78279. else {
  78280. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78281. }
  78282. break;
  78283. case 2:
  78284. if (this._checkVerticesInsteadOfIndices) {
  78285. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78286. }
  78287. else {
  78288. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78289. }
  78290. break;
  78291. }
  78292. if (otherEdgeIndex === -1) {
  78293. continue;
  78294. }
  78295. faceAdjacencies.edges[edgeIndex] = otherIndex;
  78296. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  78297. faceAdjacencies.edgesConnectedCount++;
  78298. otherFaceAdjacencies.edgesConnectedCount++;
  78299. if (faceAdjacencies.edgesConnectedCount === 3) {
  78300. break;
  78301. }
  78302. }
  78303. }
  78304. }
  78305. // Create lines
  78306. for (index = 0; index < adjacencies.length; index++) {
  78307. // 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
  78308. var current = adjacencies[index];
  78309. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  78310. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  78311. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  78312. }
  78313. // Merge into a single mesh
  78314. var engine = this._source.getScene().getEngine();
  78315. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  78316. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  78317. this._ib = engine.createIndexBuffer(this._linesIndices);
  78318. this._indicesCount = this._linesIndices.length;
  78319. };
  78320. EdgesRenderer.prototype.render = function () {
  78321. var scene = this._source.getScene();
  78322. if (!this._lineShader.isReady() || !scene.activeCamera) {
  78323. return;
  78324. }
  78325. var engine = scene.getEngine();
  78326. this._lineShader._preBind();
  78327. // VBOs
  78328. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  78329. scene.resetCachedMaterial();
  78330. this._lineShader.setColor4("color", this._source.edgesColor);
  78331. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  78332. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  78333. }
  78334. else {
  78335. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  78336. }
  78337. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  78338. this._lineShader.bind(this._source.getWorldMatrix());
  78339. // Draw order
  78340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  78341. this._lineShader.unbind();
  78342. engine.setDepthWrite(true);
  78343. };
  78344. return EdgesRenderer;
  78345. }());
  78346. BABYLON.EdgesRenderer = EdgesRenderer;
  78347. })(BABYLON || (BABYLON = {}));
  78348. //# sourceMappingURL=babylon.edgesRenderer.js.map
  78349. var BABYLON;
  78350. (function (BABYLON) {
  78351. /**
  78352. * Special Glow Blur post process only blurring the alpha channel
  78353. * It enforces keeping the most luminous color in the color channel.
  78354. */
  78355. var GlowBlurPostProcess = /** @class */ (function (_super) {
  78356. __extends(GlowBlurPostProcess, _super);
  78357. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  78358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78359. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  78360. _this.direction = direction;
  78361. _this.kernel = kernel;
  78362. _this.onApplyObservable.add(function (effect) {
  78363. effect.setFloat2("screenSize", _this.width, _this.height);
  78364. effect.setVector2("direction", _this.direction);
  78365. effect.setFloat("blurWidth", _this.kernel);
  78366. });
  78367. return _this;
  78368. }
  78369. return GlowBlurPostProcess;
  78370. }(BABYLON.PostProcess));
  78371. /**
  78372. * The highlight layer Helps adding a glow effect around a mesh.
  78373. *
  78374. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  78375. * glowy meshes to your scene.
  78376. *
  78377. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  78378. */
  78379. var HighlightLayer = /** @class */ (function () {
  78380. /**
  78381. * Instantiates a new highlight Layer and references it to the scene..
  78382. * @param name The name of the layer
  78383. * @param scene The scene to use the layer in
  78384. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  78385. */
  78386. function HighlightLayer(name, scene, options) {
  78387. this.name = name;
  78388. this._vertexBuffers = {};
  78389. this._mainTextureDesiredSize = { width: 0, height: 0 };
  78390. this._meshes = {};
  78391. this._maxSize = 0;
  78392. this._shouldRender = false;
  78393. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  78394. this._excludedMeshes = {};
  78395. /**
  78396. * Specifies whether or not the inner glow is ACTIVE in the layer.
  78397. */
  78398. this.innerGlow = true;
  78399. /**
  78400. * Specifies whether or not the outer glow is ACTIVE in the layer.
  78401. */
  78402. this.outerGlow = true;
  78403. /**
  78404. * Specifies wether the highlight layer is enabled or not.
  78405. */
  78406. this.isEnabled = true;
  78407. /**
  78408. * An event triggered when the highlight layer has been disposed.
  78409. * @type {BABYLON.Observable}
  78410. */
  78411. this.onDisposeObservable = new BABYLON.Observable();
  78412. /**
  78413. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  78414. * @type {BABYLON.Observable}
  78415. */
  78416. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  78417. /**
  78418. * An event triggered when the highlight layer is being blurred.
  78419. * @type {BABYLON.Observable}
  78420. */
  78421. this.onBeforeBlurObservable = new BABYLON.Observable();
  78422. /**
  78423. * An event triggered when the highlight layer has been blurred.
  78424. * @type {BABYLON.Observable}
  78425. */
  78426. this.onAfterBlurObservable = new BABYLON.Observable();
  78427. /**
  78428. * An event triggered when the glowing blurred texture is being merged in the scene.
  78429. * @type {BABYLON.Observable}
  78430. */
  78431. this.onBeforeComposeObservable = new BABYLON.Observable();
  78432. /**
  78433. * An event triggered when the glowing blurred texture has been merged in the scene.
  78434. * @type {BABYLON.Observable}
  78435. */
  78436. this.onAfterComposeObservable = new BABYLON.Observable();
  78437. /**
  78438. * An event triggered when the highlight layer changes its size.
  78439. * @type {BABYLON.Observable}
  78440. */
  78441. this.onSizeChangedObservable = new BABYLON.Observable();
  78442. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78443. var engine = scene.getEngine();
  78444. this._engine = engine;
  78445. this._maxSize = this._engine.getCaps().maxTextureSize;
  78446. this._scene.highlightLayers.push(this);
  78447. // Warn on stencil.
  78448. if (!this._engine.isStencilEnable) {
  78449. 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 }");
  78450. }
  78451. // Adapt options
  78452. this._options = options || {
  78453. mainTextureRatio: 0.5,
  78454. blurTextureSizeRatio: 0.5,
  78455. blurHorizontalSize: 1.0,
  78456. blurVerticalSize: 1.0,
  78457. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  78458. camera: null
  78459. };
  78460. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  78461. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  78462. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  78463. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  78464. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  78465. // VBO
  78466. var vertices = [];
  78467. vertices.push(1, 1);
  78468. vertices.push(-1, 1);
  78469. vertices.push(-1, -1);
  78470. vertices.push(1, -1);
  78471. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78473. this._createIndexBuffer();
  78474. // Effect
  78475. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  78476. // Render target
  78477. this.setMainTextureSize();
  78478. // Create Textures and post processes
  78479. this.createTextureAndPostProcesses();
  78480. }
  78481. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  78482. /**
  78483. * Gets the horizontal size of the blur.
  78484. */
  78485. get: function () {
  78486. return this._horizontalBlurPostprocess.kernel;
  78487. },
  78488. /**
  78489. * Specifies the horizontal size of the blur.
  78490. */
  78491. set: function (value) {
  78492. this._horizontalBlurPostprocess.kernel = value;
  78493. },
  78494. enumerable: true,
  78495. configurable: true
  78496. });
  78497. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  78498. /**
  78499. * Gets the vertical size of the blur.
  78500. */
  78501. get: function () {
  78502. return this._verticalBlurPostprocess.kernel;
  78503. },
  78504. /**
  78505. * Specifies the vertical size of the blur.
  78506. */
  78507. set: function (value) {
  78508. this._verticalBlurPostprocess.kernel = value;
  78509. },
  78510. enumerable: true,
  78511. configurable: true
  78512. });
  78513. Object.defineProperty(HighlightLayer.prototype, "camera", {
  78514. /**
  78515. * Gets the camera attached to the layer.
  78516. */
  78517. get: function () {
  78518. return this._options.camera;
  78519. },
  78520. enumerable: true,
  78521. configurable: true
  78522. });
  78523. HighlightLayer.prototype._createIndexBuffer = function () {
  78524. var engine = this._scene.getEngine();
  78525. // Indices
  78526. var indices = [];
  78527. indices.push(0);
  78528. indices.push(1);
  78529. indices.push(2);
  78530. indices.push(0);
  78531. indices.push(2);
  78532. indices.push(3);
  78533. this._indexBuffer = engine.createIndexBuffer(indices);
  78534. };
  78535. HighlightLayer.prototype._rebuild = function () {
  78536. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78537. if (vb) {
  78538. vb._rebuild();
  78539. }
  78540. this._createIndexBuffer();
  78541. };
  78542. /**
  78543. * Creates the render target textures and post processes used in the highlight layer.
  78544. */
  78545. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  78546. var _this = this;
  78547. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  78548. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  78549. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  78550. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  78551. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  78552. width: this._mainTextureDesiredSize.width,
  78553. height: this._mainTextureDesiredSize.height
  78554. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78555. this._mainTexture.activeCamera = this._options.camera;
  78556. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78557. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78558. this._mainTexture.anisotropicFilteringLevel = 1;
  78559. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78560. this._mainTexture.renderParticles = false;
  78561. this._mainTexture.renderList = null;
  78562. this._mainTexture.ignoreCameraViewport = true;
  78563. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  78564. width: blurTextureWidth,
  78565. height: blurTextureHeight
  78566. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78567. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78568. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78569. this._blurTexture.anisotropicFilteringLevel = 16;
  78570. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78571. this._blurTexture.renderParticles = false;
  78572. this._blurTexture.ignoreCameraViewport = true;
  78573. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78574. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  78575. effect.setTexture("textureSampler", _this._mainTexture);
  78576. });
  78577. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  78578. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78579. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78580. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78581. });
  78582. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78583. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78584. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78585. });
  78586. }
  78587. else {
  78588. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78589. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78590. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78591. });
  78592. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78593. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78594. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78595. });
  78596. }
  78597. this._mainTexture.onAfterUnbindObservable.add(function () {
  78598. _this.onBeforeBlurObservable.notifyObservers(_this);
  78599. var internalTexture = _this._blurTexture.getInternalTexture();
  78600. if (internalTexture) {
  78601. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  78602. }
  78603. _this.onAfterBlurObservable.notifyObservers(_this);
  78604. });
  78605. // Custom render function
  78606. var renderSubMesh = function (subMesh) {
  78607. if (!_this._meshes) {
  78608. return;
  78609. }
  78610. var material = subMesh.getMaterial();
  78611. var mesh = subMesh.getRenderingMesh();
  78612. var scene = _this._scene;
  78613. var engine = scene.getEngine();
  78614. if (!material) {
  78615. return;
  78616. }
  78617. // Do not block in blend mode.
  78618. if (material.needAlphaBlendingForMesh(mesh)) {
  78619. return;
  78620. }
  78621. // Culling
  78622. engine.setState(material.backFaceCulling);
  78623. // Managing instances
  78624. var batch = mesh._getInstancesRenderList(subMesh._id);
  78625. if (batch.mustReturn) {
  78626. return;
  78627. }
  78628. // Excluded Mesh
  78629. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78630. return;
  78631. }
  78632. ;
  78633. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78634. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  78635. var emissiveTexture = null;
  78636. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78637. emissiveTexture = material.emissiveTexture;
  78638. }
  78639. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  78640. engine.enableEffect(_this._glowMapGenerationEffect);
  78641. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  78642. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  78643. if (highlightLayerMesh) {
  78644. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  78645. }
  78646. else {
  78647. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  78648. }
  78649. // Alpha test
  78650. if (material && material.needAlphaTesting()) {
  78651. var alphaTexture = material.getAlphaTestTexture();
  78652. if (alphaTexture) {
  78653. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  78654. var textureMatrix = alphaTexture.getTextureMatrix();
  78655. if (textureMatrix) {
  78656. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  78657. }
  78658. }
  78659. }
  78660. // Glow emissive only
  78661. if (emissiveTexture) {
  78662. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  78663. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  78664. }
  78665. // Bones
  78666. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78667. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78668. }
  78669. // Draw
  78670. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  78671. }
  78672. else {
  78673. // Need to reset refresh rate of the shadowMap
  78674. _this._mainTexture.resetRefreshCounter();
  78675. }
  78676. };
  78677. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78678. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  78679. var index;
  78680. var engine = _this._scene.getEngine();
  78681. if (depthOnlySubMeshes.length) {
  78682. engine.setColorWrite(false);
  78683. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78684. renderSubMesh(depthOnlySubMeshes.data[index]);
  78685. }
  78686. engine.setColorWrite(true);
  78687. }
  78688. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78689. renderSubMesh(opaqueSubMeshes.data[index]);
  78690. }
  78691. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78692. renderSubMesh(alphaTestSubMeshes.data[index]);
  78693. }
  78694. for (index = 0; index < transparentSubMeshes.length; index++) {
  78695. renderSubMesh(transparentSubMeshes.data[index]);
  78696. }
  78697. };
  78698. this._mainTexture.onClearObservable.add(function (engine) {
  78699. engine.clear(HighlightLayer.neutralColor, true, true, true);
  78700. });
  78701. };
  78702. /**
  78703. * Checks for the readiness of the element composing the layer.
  78704. * @param subMesh the mesh to check for
  78705. * @param useInstances specify wether or not to use instances to render the mesh
  78706. * @param emissiveTexture the associated emissive texture used to generate the glow
  78707. * @return true if ready otherwise, false
  78708. */
  78709. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  78710. var material = subMesh.getMaterial();
  78711. var mesh = subMesh.getRenderingMesh();
  78712. if (!material || !mesh || !this._meshes) {
  78713. return false;
  78714. }
  78715. var emissiveTexture = null;
  78716. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  78717. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78718. emissiveTexture = material.emissiveTexture;
  78719. }
  78720. return this._isReady(subMesh, useInstances, emissiveTexture);
  78721. };
  78722. /**
  78723. * Checks for the readiness of the element composing the layer.
  78724. * @param subMesh the mesh to check for
  78725. * @param useInstances specify wether or not to use instances to render the mesh
  78726. * @param emissiveTexture the associated emissive texture used to generate the glow
  78727. * @return true if ready otherwise, false
  78728. */
  78729. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  78730. var material = subMesh.getMaterial();
  78731. if (!material) {
  78732. return false;
  78733. }
  78734. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  78735. return false;
  78736. }
  78737. var defines = [];
  78738. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78739. var mesh = subMesh.getMesh();
  78740. var uv1 = false;
  78741. var uv2 = false;
  78742. // Alpha test
  78743. if (material && material.needAlphaTesting()) {
  78744. var alphaTexture = material.getAlphaTestTexture();
  78745. if (alphaTexture) {
  78746. defines.push("#define ALPHATEST");
  78747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  78748. alphaTexture.coordinatesIndex === 1) {
  78749. defines.push("#define DIFFUSEUV2");
  78750. uv2 = true;
  78751. }
  78752. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78753. defines.push("#define DIFFUSEUV1");
  78754. uv1 = true;
  78755. }
  78756. }
  78757. }
  78758. // Emissive
  78759. if (emissiveTexture) {
  78760. defines.push("#define EMISSIVE");
  78761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  78762. emissiveTexture.coordinatesIndex === 1) {
  78763. defines.push("#define EMISSIVEUV2");
  78764. uv2 = true;
  78765. }
  78766. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78767. defines.push("#define EMISSIVEUV1");
  78768. uv1 = true;
  78769. }
  78770. }
  78771. if (uv1) {
  78772. attribs.push(BABYLON.VertexBuffer.UVKind);
  78773. defines.push("#define UV1");
  78774. }
  78775. if (uv2) {
  78776. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78777. defines.push("#define UV2");
  78778. }
  78779. // Bones
  78780. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78781. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78782. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78783. if (mesh.numBoneInfluencers > 4) {
  78784. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78785. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78786. }
  78787. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78788. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78789. }
  78790. else {
  78791. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78792. }
  78793. // Instances
  78794. if (useInstances) {
  78795. defines.push("#define INSTANCES");
  78796. attribs.push("world0");
  78797. attribs.push("world1");
  78798. attribs.push("world2");
  78799. attribs.push("world3");
  78800. }
  78801. // Get correct effect
  78802. var join = defines.join("\n");
  78803. if (this._cachedDefines !== join) {
  78804. this._cachedDefines = join;
  78805. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  78806. }
  78807. return this._glowMapGenerationEffect.isReady();
  78808. };
  78809. /**
  78810. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  78811. */
  78812. HighlightLayer.prototype.render = function () {
  78813. var currentEffect = this._glowMapMergeEffect;
  78814. // Check
  78815. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  78816. return;
  78817. var engine = this._scene.getEngine();
  78818. this.onBeforeComposeObservable.notifyObservers(this);
  78819. // Render
  78820. engine.enableEffect(currentEffect);
  78821. engine.setState(false);
  78822. // Cache
  78823. var previousStencilBuffer = engine.getStencilBuffer();
  78824. var previousStencilFunction = engine.getStencilFunction();
  78825. var previousStencilMask = engine.getStencilMask();
  78826. var previousStencilOperationPass = engine.getStencilOperationPass();
  78827. var previousStencilOperationFail = engine.getStencilOperationFail();
  78828. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  78829. var previousAlphaMode = engine.getAlphaMode();
  78830. // Texture
  78831. currentEffect.setTexture("textureSampler", this._blurTexture);
  78832. // VBOs
  78833. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78834. // Stencil operations
  78835. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  78836. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  78837. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  78838. // Draw order
  78839. engine.setAlphaMode(this._options.alphaBlendingMode);
  78840. engine.setStencilMask(0x00);
  78841. engine.setStencilBuffer(true);
  78842. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  78843. if (this.outerGlow) {
  78844. currentEffect.setFloat("offset", 0);
  78845. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  78846. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78847. }
  78848. if (this.innerGlow) {
  78849. currentEffect.setFloat("offset", 1);
  78850. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  78851. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78852. }
  78853. // Restore Cache
  78854. engine.setStencilFunction(previousStencilFunction);
  78855. engine.setStencilMask(previousStencilMask);
  78856. engine.setAlphaMode(previousAlphaMode);
  78857. engine.setStencilBuffer(previousStencilBuffer);
  78858. engine.setStencilOperationPass(previousStencilOperationPass);
  78859. engine.setStencilOperationFail(previousStencilOperationFail);
  78860. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  78861. engine._stencilState.reset();
  78862. this.onAfterComposeObservable.notifyObservers(this);
  78863. // Handle size changes.
  78864. var size = this._mainTexture.getSize();
  78865. this.setMainTextureSize();
  78866. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  78867. // Recreate RTT and post processes on size change.
  78868. this.onSizeChangedObservable.notifyObservers(this);
  78869. this.disposeTextureAndPostProcesses();
  78870. this.createTextureAndPostProcesses();
  78871. }
  78872. };
  78873. /**
  78874. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  78875. * @param mesh The mesh to exclude from the highlight layer
  78876. */
  78877. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  78878. if (!this._excludedMeshes) {
  78879. return;
  78880. }
  78881. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  78882. if (!meshExcluded) {
  78883. this._excludedMeshes[mesh.uniqueId] = {
  78884. mesh: mesh,
  78885. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  78886. mesh.getEngine().setStencilBuffer(false);
  78887. }),
  78888. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  78889. mesh.getEngine().setStencilBuffer(true);
  78890. }),
  78891. };
  78892. }
  78893. };
  78894. /**
  78895. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  78896. * @param mesh The mesh to highlight
  78897. */
  78898. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  78899. if (!this._excludedMeshes) {
  78900. return;
  78901. }
  78902. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  78903. if (meshExcluded) {
  78904. if (meshExcluded.beforeRender) {
  78905. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  78906. }
  78907. if (meshExcluded.afterRender) {
  78908. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  78909. }
  78910. }
  78911. this._excludedMeshes[mesh.uniqueId] = null;
  78912. };
  78913. /**
  78914. * Determine if a given mesh will be highlighted by the current HighlightLayer
  78915. * @param mesh mesh to test
  78916. * @returns true if the mesh will be highlighted by the current HighlightLayer
  78917. */
  78918. HighlightLayer.prototype.hasMesh = function (mesh) {
  78919. if (!this._meshes) {
  78920. return false;
  78921. }
  78922. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  78923. };
  78924. /**
  78925. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  78926. * @param mesh The mesh to highlight
  78927. * @param color The color of the highlight
  78928. * @param glowEmissiveOnly Extract the glow from the emissive texture
  78929. */
  78930. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  78931. var _this = this;
  78932. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  78933. if (!this._meshes) {
  78934. return;
  78935. }
  78936. var meshHighlight = this._meshes[mesh.uniqueId];
  78937. if (meshHighlight) {
  78938. meshHighlight.color = color;
  78939. }
  78940. else {
  78941. this._meshes[mesh.uniqueId] = {
  78942. mesh: mesh,
  78943. color: color,
  78944. // Lambda required for capture due to Observable this context
  78945. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  78946. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78947. _this.defaultStencilReference(mesh);
  78948. }
  78949. else {
  78950. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  78951. }
  78952. }),
  78953. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  78954. glowEmissiveOnly: glowEmissiveOnly
  78955. };
  78956. }
  78957. this._shouldRender = true;
  78958. };
  78959. /**
  78960. * Remove a mesh from the highlight layer in order to make it stop glowing.
  78961. * @param mesh The mesh to highlight
  78962. */
  78963. HighlightLayer.prototype.removeMesh = function (mesh) {
  78964. if (!this._meshes) {
  78965. return;
  78966. }
  78967. var meshHighlight = this._meshes[mesh.uniqueId];
  78968. if (meshHighlight) {
  78969. if (meshHighlight.observerHighlight) {
  78970. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  78971. }
  78972. if (meshHighlight.observerDefault) {
  78973. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  78974. }
  78975. delete this._meshes[mesh.uniqueId];
  78976. }
  78977. this._shouldRender = false;
  78978. for (var meshHighlightToCheck in this._meshes) {
  78979. if (this._meshes[meshHighlightToCheck]) {
  78980. this._shouldRender = true;
  78981. break;
  78982. }
  78983. }
  78984. };
  78985. /**
  78986. * Returns true if the layer contains information to display, otherwise false.
  78987. */
  78988. HighlightLayer.prototype.shouldRender = function () {
  78989. return this.isEnabled && this._shouldRender;
  78990. };
  78991. /**
  78992. * Sets the main texture desired size which is the closest power of two
  78993. * of the engine canvas size.
  78994. */
  78995. HighlightLayer.prototype.setMainTextureSize = function () {
  78996. if (this._options.mainTextureFixedSize) {
  78997. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  78998. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  78999. }
  79000. else {
  79001. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79002. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79003. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79004. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79005. }
  79006. };
  79007. /**
  79008. * Force the stencil to the normal expected value for none glowing parts
  79009. */
  79010. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79011. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79012. };
  79013. /**
  79014. * Dispose only the render target textures and post process.
  79015. */
  79016. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79017. this._blurTexture.dispose();
  79018. this._mainTexture.dispose();
  79019. this._downSamplePostprocess.dispose();
  79020. this._horizontalBlurPostprocess.dispose();
  79021. this._verticalBlurPostprocess.dispose();
  79022. };
  79023. /**
  79024. * Dispose the highlight layer and free resources.
  79025. */
  79026. HighlightLayer.prototype.dispose = function () {
  79027. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79028. if (vertexBuffer) {
  79029. vertexBuffer.dispose();
  79030. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79031. }
  79032. if (this._indexBuffer) {
  79033. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79034. this._indexBuffer = null;
  79035. }
  79036. // Clean textures and post processes
  79037. this.disposeTextureAndPostProcesses();
  79038. if (this._meshes) {
  79039. // Clean mesh references
  79040. for (var id in this._meshes) {
  79041. var meshHighlight = this._meshes[id];
  79042. if (meshHighlight && meshHighlight.mesh) {
  79043. if (meshHighlight.observerHighlight) {
  79044. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79045. }
  79046. if (meshHighlight.observerDefault) {
  79047. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79048. }
  79049. }
  79050. }
  79051. this._meshes = null;
  79052. }
  79053. if (this._excludedMeshes) {
  79054. for (var id in this._excludedMeshes) {
  79055. var meshHighlight = this._excludedMeshes[id];
  79056. if (meshHighlight) {
  79057. if (meshHighlight.beforeRender) {
  79058. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79059. }
  79060. if (meshHighlight.afterRender) {
  79061. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79062. }
  79063. }
  79064. }
  79065. this._excludedMeshes = null;
  79066. }
  79067. // Remove from scene
  79068. var index = this._scene.highlightLayers.indexOf(this, 0);
  79069. if (index > -1) {
  79070. this._scene.highlightLayers.splice(index, 1);
  79071. }
  79072. // Callback
  79073. this.onDisposeObservable.notifyObservers(this);
  79074. this.onDisposeObservable.clear();
  79075. this.onBeforeRenderMainTextureObservable.clear();
  79076. this.onBeforeBlurObservable.clear();
  79077. this.onBeforeComposeObservable.clear();
  79078. this.onAfterComposeObservable.clear();
  79079. this.onSizeChangedObservable.clear();
  79080. };
  79081. /**
  79082. * The neutral color used during the preparation of the glow effect.
  79083. * This is black by default as the blend operation is a blend operation.
  79084. */
  79085. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79086. /**
  79087. * Stencil value used for glowing meshes.
  79088. */
  79089. HighlightLayer.glowingMeshStencilReference = 0x02;
  79090. /**
  79091. * Stencil value used for the other meshes in the scene.
  79092. */
  79093. HighlightLayer.normalMeshStencilReference = 0x01;
  79094. return HighlightLayer;
  79095. }());
  79096. BABYLON.HighlightLayer = HighlightLayer;
  79097. })(BABYLON || (BABYLON = {}));
  79098. //# sourceMappingURL=babylon.highlightlayer.js.map
  79099. var BABYLON;
  79100. (function (BABYLON) {
  79101. /**
  79102. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79103. */
  79104. var AssetTaskState;
  79105. (function (AssetTaskState) {
  79106. /**
  79107. * Initialization
  79108. */
  79109. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79110. /**
  79111. * Running
  79112. */
  79113. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79114. /**
  79115. * Done
  79116. */
  79117. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79118. /**
  79119. * Error
  79120. */
  79121. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79122. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79123. /**
  79124. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79125. */
  79126. var AbstractAssetTask = /** @class */ (function () {
  79127. /**
  79128. * Creates a new {BABYLON.AssetsManager}
  79129. * @param name defines the name of the task
  79130. */
  79131. function AbstractAssetTask(
  79132. /**
  79133. * Task name
  79134. */ name) {
  79135. this.name = name;
  79136. this._isCompleted = false;
  79137. this._taskState = AssetTaskState.INIT;
  79138. }
  79139. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79140. /**
  79141. * Get if the task is completed
  79142. */
  79143. get: function () {
  79144. return this._isCompleted;
  79145. },
  79146. enumerable: true,
  79147. configurable: true
  79148. });
  79149. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79150. /**
  79151. * Gets the current state of the task
  79152. */
  79153. get: function () {
  79154. return this._taskState;
  79155. },
  79156. enumerable: true,
  79157. configurable: true
  79158. });
  79159. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79160. /**
  79161. * Gets the current error object (if task is in error)
  79162. */
  79163. get: function () {
  79164. return this._errorObject;
  79165. },
  79166. enumerable: true,
  79167. configurable: true
  79168. });
  79169. /**
  79170. * Internal only
  79171. * @ignore
  79172. */
  79173. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79174. if (this._errorObject) {
  79175. return;
  79176. }
  79177. this._errorObject = {
  79178. message: message,
  79179. exception: exception
  79180. };
  79181. };
  79182. /**
  79183. * Execute the current task
  79184. * @param scene defines the scene where you want your assets to be loaded
  79185. * @param onSuccess is a callback called when the task is successfully executed
  79186. * @param onError is a callback called if an error occurs
  79187. */
  79188. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79189. var _this = this;
  79190. this._taskState = AssetTaskState.RUNNING;
  79191. this.runTask(scene, function () {
  79192. _this.onDoneCallback(onSuccess, onError);
  79193. }, function (msg, exception) {
  79194. _this.onErrorCallback(onError, msg, exception);
  79195. });
  79196. };
  79197. /**
  79198. * Execute the current task
  79199. * @param scene defines the scene where you want your assets to be loaded
  79200. * @param onSuccess is a callback called when the task is successfully executed
  79201. * @param onError is a callback called if an error occurs
  79202. */
  79203. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79204. throw new Error("runTask is not implemented");
  79205. };
  79206. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79207. this._taskState = AssetTaskState.ERROR;
  79208. this._errorObject = {
  79209. message: message,
  79210. exception: exception
  79211. };
  79212. if (this.onError) {
  79213. this.onError(this, message, exception);
  79214. }
  79215. onError();
  79216. };
  79217. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79218. try {
  79219. this._taskState = AssetTaskState.DONE;
  79220. this._isCompleted = true;
  79221. if (this.onSuccess) {
  79222. this.onSuccess(this);
  79223. }
  79224. onSuccess();
  79225. }
  79226. catch (e) {
  79227. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79228. }
  79229. };
  79230. return AbstractAssetTask;
  79231. }());
  79232. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79233. /**
  79234. * Class used to share progress information about assets loading
  79235. */
  79236. var AssetsProgressEvent = /** @class */ (function () {
  79237. /**
  79238. * Creates a {BABYLON.AssetsProgressEvent}
  79239. * @param remainingCount defines the number of remaining tasks to process
  79240. * @param totalCount defines the total number of tasks
  79241. * @param task defines the task that was just processed
  79242. */
  79243. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79244. this.remainingCount = remainingCount;
  79245. this.totalCount = totalCount;
  79246. this.task = task;
  79247. }
  79248. return AssetsProgressEvent;
  79249. }());
  79250. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79251. /**
  79252. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79253. */
  79254. var MeshAssetTask = /** @class */ (function (_super) {
  79255. __extends(MeshAssetTask, _super);
  79256. /**
  79257. * Creates a new {BABYLON.MeshAssetTask}
  79258. * @param name defines the name of the task
  79259. * @param meshesNames defines the list of mesh's names you want to load
  79260. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79261. * @param sceneFilename defines the filename of the scene to load from
  79262. */
  79263. function MeshAssetTask(
  79264. /**
  79265. * Defines the name of the task
  79266. */
  79267. name,
  79268. /**
  79269. * Defines the list of mesh's names you want to load
  79270. */
  79271. meshesNames,
  79272. /**
  79273. * Defines the root url to use as a base to load your meshes and associated resources
  79274. */
  79275. rootUrl,
  79276. /**
  79277. * Defines the filename of the scene to load from
  79278. */
  79279. sceneFilename) {
  79280. var _this = _super.call(this, name) || this;
  79281. _this.name = name;
  79282. _this.meshesNames = meshesNames;
  79283. _this.rootUrl = rootUrl;
  79284. _this.sceneFilename = sceneFilename;
  79285. return _this;
  79286. }
  79287. /**
  79288. * Execute the current task
  79289. * @param scene defines the scene where you want your assets to be loaded
  79290. * @param onSuccess is a callback called when the task is successfully executed
  79291. * @param onError is a callback called if an error occurs
  79292. */
  79293. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79294. var _this = this;
  79295. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  79296. _this.loadedMeshes = meshes;
  79297. _this.loadedParticleSystems = particleSystems;
  79298. _this.loadedSkeletons = skeletons;
  79299. onSuccess();
  79300. }, null, function (scene, message, exception) {
  79301. onError(message, exception);
  79302. });
  79303. };
  79304. return MeshAssetTask;
  79305. }(AbstractAssetTask));
  79306. BABYLON.MeshAssetTask = MeshAssetTask;
  79307. /**
  79308. * Define a task used by {BABYLON.AssetsManager} to load text content
  79309. */
  79310. var TextFileAssetTask = /** @class */ (function (_super) {
  79311. __extends(TextFileAssetTask, _super);
  79312. /**
  79313. * Creates a new TextFileAssetTask object
  79314. * @param name defines the name of the task
  79315. * @param url defines the location of the file to load
  79316. */
  79317. function TextFileAssetTask(
  79318. /**
  79319. * Defines the name of the task
  79320. */
  79321. name,
  79322. /**
  79323. * Defines the location of the file to load
  79324. */
  79325. url) {
  79326. var _this = _super.call(this, name) || this;
  79327. _this.name = name;
  79328. _this.url = url;
  79329. return _this;
  79330. }
  79331. /**
  79332. * Execute the current task
  79333. * @param scene defines the scene where you want your assets to be loaded
  79334. * @param onSuccess is a callback called when the task is successfully executed
  79335. * @param onError is a callback called if an error occurs
  79336. */
  79337. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79338. var _this = this;
  79339. scene._loadFile(this.url, function (data) {
  79340. _this.text = data;
  79341. onSuccess();
  79342. }, undefined, false, true, function (request, exception) {
  79343. if (request) {
  79344. onError(request.status + " " + request.statusText, exception);
  79345. }
  79346. });
  79347. };
  79348. return TextFileAssetTask;
  79349. }(AbstractAssetTask));
  79350. BABYLON.TextFileAssetTask = TextFileAssetTask;
  79351. /**
  79352. * Define a task used by {BABYLON.AssetsManager} to load binary data
  79353. */
  79354. var BinaryFileAssetTask = /** @class */ (function (_super) {
  79355. __extends(BinaryFileAssetTask, _super);
  79356. /**
  79357. * Creates a new BinaryFileAssetTask object
  79358. * @param name defines the name of the new task
  79359. * @param url defines the location of the file to load
  79360. */
  79361. function BinaryFileAssetTask(
  79362. /**
  79363. * Defines the name of the task
  79364. */
  79365. name,
  79366. /**
  79367. * Defines the location of the file to load
  79368. */
  79369. url) {
  79370. var _this = _super.call(this, name) || this;
  79371. _this.name = name;
  79372. _this.url = url;
  79373. return _this;
  79374. }
  79375. /**
  79376. * Execute the current task
  79377. * @param scene defines the scene where you want your assets to be loaded
  79378. * @param onSuccess is a callback called when the task is successfully executed
  79379. * @param onError is a callback called if an error occurs
  79380. */
  79381. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79382. var _this = this;
  79383. scene._loadFile(this.url, function (data) {
  79384. _this.data = data;
  79385. onSuccess();
  79386. }, undefined, true, true, function (request, exception) {
  79387. if (request) {
  79388. onError(request.status + " " + request.statusText, exception);
  79389. }
  79390. });
  79391. };
  79392. return BinaryFileAssetTask;
  79393. }(AbstractAssetTask));
  79394. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  79395. /**
  79396. * Define a task used by {BABYLON.AssetsManager} to load images
  79397. */
  79398. var ImageAssetTask = /** @class */ (function (_super) {
  79399. __extends(ImageAssetTask, _super);
  79400. /**
  79401. * Creates a new ImageAssetTask
  79402. * @param name defines the name of the task
  79403. * @param url defines the location of the image to load
  79404. */
  79405. function ImageAssetTask(
  79406. /**
  79407. * Defines the name of the task
  79408. */
  79409. name,
  79410. /**
  79411. * Defines the location of the image to load
  79412. */
  79413. url) {
  79414. var _this = _super.call(this, name) || this;
  79415. _this.name = name;
  79416. _this.url = url;
  79417. return _this;
  79418. }
  79419. /**
  79420. * Execute the current task
  79421. * @param scene defines the scene where you want your assets to be loaded
  79422. * @param onSuccess is a callback called when the task is successfully executed
  79423. * @param onError is a callback called if an error occurs
  79424. */
  79425. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79426. var _this = this;
  79427. var img = new Image();
  79428. BABYLON.Tools.SetCorsBehavior(this.url, img);
  79429. img.onload = function () {
  79430. _this.image = img;
  79431. onSuccess();
  79432. };
  79433. img.onerror = function (err) {
  79434. onError("Error loading image", err);
  79435. };
  79436. img.src = this.url;
  79437. };
  79438. return ImageAssetTask;
  79439. }(AbstractAssetTask));
  79440. BABYLON.ImageAssetTask = ImageAssetTask;
  79441. /**
  79442. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  79443. */
  79444. var TextureAssetTask = /** @class */ (function (_super) {
  79445. __extends(TextureAssetTask, _super);
  79446. /**
  79447. * Creates a new TextureAssetTask object
  79448. * @param name defines the name of the task
  79449. * @param url defines the location of the file to load
  79450. * @param noMipmap defines if mipmap should not be generated (default is false)
  79451. * @param invertY defines if texture must be inverted on Y axis (default is false)
  79452. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79453. */
  79454. function TextureAssetTask(
  79455. /**
  79456. * Defines the name of the task
  79457. */
  79458. name,
  79459. /**
  79460. * Defines the location of the file to load
  79461. */
  79462. url,
  79463. /**
  79464. * Defines if mipmap should not be generated (default is false)
  79465. */
  79466. noMipmap,
  79467. /**
  79468. * Defines if texture must be inverted on Y axis (default is false)
  79469. */
  79470. invertY,
  79471. /**
  79472. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79473. */
  79474. samplingMode) {
  79475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79476. var _this = _super.call(this, name) || this;
  79477. _this.name = name;
  79478. _this.url = url;
  79479. _this.noMipmap = noMipmap;
  79480. _this.invertY = invertY;
  79481. _this.samplingMode = samplingMode;
  79482. return _this;
  79483. }
  79484. /**
  79485. * Execute the current task
  79486. * @param scene defines the scene where you want your assets to be loaded
  79487. * @param onSuccess is a callback called when the task is successfully executed
  79488. * @param onError is a callback called if an error occurs
  79489. */
  79490. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79491. var onload = function () {
  79492. onSuccess();
  79493. };
  79494. var onerror = function (message, exception) {
  79495. onError(message, exception);
  79496. };
  79497. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  79498. };
  79499. return TextureAssetTask;
  79500. }(AbstractAssetTask));
  79501. BABYLON.TextureAssetTask = TextureAssetTask;
  79502. /**
  79503. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  79504. */
  79505. var CubeTextureAssetTask = /** @class */ (function (_super) {
  79506. __extends(CubeTextureAssetTask, _super);
  79507. /**
  79508. * Creates a new CubeTextureAssetTask
  79509. * @param name defines the name of the task
  79510. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79511. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79512. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79513. * @param files defines the explicit list of files (undefined by default)
  79514. */
  79515. function CubeTextureAssetTask(
  79516. /**
  79517. * Defines the name of the task
  79518. */
  79519. name,
  79520. /**
  79521. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79522. */
  79523. url,
  79524. /**
  79525. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79526. */
  79527. extensions,
  79528. /**
  79529. * Defines if mipmaps should not be generated (default is false)
  79530. */
  79531. noMipmap,
  79532. /**
  79533. * Defines the explicit list of files (undefined by default)
  79534. */
  79535. files) {
  79536. var _this = _super.call(this, name) || this;
  79537. _this.name = name;
  79538. _this.url = url;
  79539. _this.extensions = extensions;
  79540. _this.noMipmap = noMipmap;
  79541. _this.files = files;
  79542. return _this;
  79543. }
  79544. /**
  79545. * Execute the current task
  79546. * @param scene defines the scene where you want your assets to be loaded
  79547. * @param onSuccess is a callback called when the task is successfully executed
  79548. * @param onError is a callback called if an error occurs
  79549. */
  79550. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79551. var onload = function () {
  79552. onSuccess();
  79553. };
  79554. var onerror = function (message, exception) {
  79555. onError(message, exception);
  79556. };
  79557. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  79558. };
  79559. return CubeTextureAssetTask;
  79560. }(AbstractAssetTask));
  79561. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  79562. /**
  79563. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  79564. */
  79565. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  79566. __extends(HDRCubeTextureAssetTask, _super);
  79567. /**
  79568. * Creates a new HDRCubeTextureAssetTask object
  79569. * @param name defines the name of the task
  79570. * @param url defines the location of the file to load
  79571. * @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.
  79572. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79573. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79574. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  79575. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79576. */
  79577. function HDRCubeTextureAssetTask(
  79578. /**
  79579. * Defines the name of the task
  79580. */
  79581. name,
  79582. /**
  79583. * Defines the location of the file to load
  79584. */
  79585. url,
  79586. /**
  79587. * 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.
  79588. */
  79589. size,
  79590. /**
  79591. * Defines if mipmaps should not be generated (default is false)
  79592. */
  79593. noMipmap,
  79594. /**
  79595. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79596. */
  79597. generateHarmonics,
  79598. /**
  79599. * 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)
  79600. */
  79601. useInGammaSpace,
  79602. /**
  79603. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79604. */
  79605. usePMREMGenerator) {
  79606. if (noMipmap === void 0) { noMipmap = false; }
  79607. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79608. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79609. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79610. var _this = _super.call(this, name) || this;
  79611. _this.name = name;
  79612. _this.url = url;
  79613. _this.size = size;
  79614. _this.noMipmap = noMipmap;
  79615. _this.generateHarmonics = generateHarmonics;
  79616. _this.useInGammaSpace = useInGammaSpace;
  79617. _this.usePMREMGenerator = usePMREMGenerator;
  79618. return _this;
  79619. }
  79620. /**
  79621. * Execute the current task
  79622. * @param scene defines the scene where you want your assets to be loaded
  79623. * @param onSuccess is a callback called when the task is successfully executed
  79624. * @param onError is a callback called if an error occurs
  79625. */
  79626. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79627. var onload = function () {
  79628. onSuccess();
  79629. };
  79630. var onerror = function (message, exception) {
  79631. onError(message, exception);
  79632. };
  79633. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  79634. };
  79635. return HDRCubeTextureAssetTask;
  79636. }(AbstractAssetTask));
  79637. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  79638. /**
  79639. * This class can be used to easily import assets into a scene
  79640. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  79641. */
  79642. var AssetsManager = /** @class */ (function () {
  79643. /**
  79644. * Creates a new AssetsManager
  79645. * @param scene defines the scene to work on
  79646. */
  79647. function AssetsManager(scene) {
  79648. this._isLoading = false;
  79649. this._tasks = new Array();
  79650. this._waitingTasksCount = 0;
  79651. this._totalTasksCount = 0;
  79652. /**
  79653. * Observable called when all tasks are processed
  79654. */
  79655. this.onTaskSuccessObservable = new BABYLON.Observable();
  79656. /**
  79657. * Observable called when a task had an error
  79658. */
  79659. this.onTaskErrorObservable = new BABYLON.Observable();
  79660. /**
  79661. * Observable called when a task is successful
  79662. */
  79663. this.onTasksDoneObservable = new BABYLON.Observable();
  79664. /**
  79665. * Observable called when a task is done (whatever the result is)
  79666. */
  79667. this.onProgressObservable = new BABYLON.Observable();
  79668. /**
  79669. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  79670. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  79671. */
  79672. this.useDefaultLoadingScreen = true;
  79673. this._scene = scene;
  79674. }
  79675. /**
  79676. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  79677. * @param taskName defines the name of the new task
  79678. * @param meshesNames defines the name of meshes to load
  79679. * @param rootUrl defines the root url to use to locate files
  79680. * @param sceneFilename defines the filename of the scene file
  79681. * @returns a new {BABYLON.MeshAssetTask} object
  79682. */
  79683. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  79684. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  79685. this._tasks.push(task);
  79686. return task;
  79687. };
  79688. /**
  79689. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  79690. * @param taskName defines the name of the new task
  79691. * @param url defines the url of the file to load
  79692. * @returns a new {BABYLON.TextFileAssetTask} object
  79693. */
  79694. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  79695. var task = new TextFileAssetTask(taskName, url);
  79696. this._tasks.push(task);
  79697. return task;
  79698. };
  79699. /**
  79700. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  79701. * @param taskName defines the name of the new task
  79702. * @param url defines the url of the file to load
  79703. * @returns a new {BABYLON.BinaryFileAssetTask} object
  79704. */
  79705. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  79706. var task = new BinaryFileAssetTask(taskName, url);
  79707. this._tasks.push(task);
  79708. return task;
  79709. };
  79710. /**
  79711. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  79712. * @param taskName defines the name of the new task
  79713. * @param url defines the url of the file to load
  79714. * @returns a new {BABYLON.ImageAssetTask} object
  79715. */
  79716. AssetsManager.prototype.addImageTask = function (taskName, url) {
  79717. var task = new ImageAssetTask(taskName, url);
  79718. this._tasks.push(task);
  79719. return task;
  79720. };
  79721. /**
  79722. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  79723. * @param taskName defines the name of the new task
  79724. * @param url defines the url of the file to load
  79725. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79726. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  79727. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  79728. * @returns a new {BABYLON.TextureAssetTask} object
  79729. */
  79730. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  79731. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79732. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  79733. this._tasks.push(task);
  79734. return task;
  79735. };
  79736. /**
  79737. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  79738. * @param taskName defines the name of the new task
  79739. * @param url defines the url of the file to load
  79740. * @param extensions defines the extension to use to load the cube map (can be null)
  79741. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79742. * @param files defines the list of files to load (can be null)
  79743. * @returns a new {BABYLON.CubeTextureAssetTask} object
  79744. */
  79745. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  79746. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  79747. this._tasks.push(task);
  79748. return task;
  79749. };
  79750. /**
  79751. *
  79752. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  79753. * @param taskName defines the name of the new task
  79754. * @param url defines the url of the file to load
  79755. * @param size defines the size you want for the cubemap (can be null)
  79756. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79757. * @param generateHarmonics defines if you want to automatically generate (true by default)
  79758. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  79759. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  79760. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  79761. */
  79762. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  79763. if (noMipmap === void 0) { noMipmap = false; }
  79764. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79765. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79766. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79767. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  79768. this._tasks.push(task);
  79769. return task;
  79770. };
  79771. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  79772. var _this = this;
  79773. this._waitingTasksCount--;
  79774. try {
  79775. if (task.taskState === AssetTaskState.DONE) {
  79776. // Let's remove successfull tasks
  79777. BABYLON.Tools.SetImmediate(function () {
  79778. var index = _this._tasks.indexOf(task);
  79779. if (index > -1) {
  79780. _this._tasks.splice(index, 1);
  79781. }
  79782. });
  79783. }
  79784. if (this.onProgress) {
  79785. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  79786. }
  79787. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  79788. }
  79789. catch (e) {
  79790. BABYLON.Tools.Error("Error running progress callbacks.");
  79791. console.log(e);
  79792. }
  79793. if (this._waitingTasksCount === 0) {
  79794. try {
  79795. if (this.onFinish) {
  79796. this.onFinish(this._tasks);
  79797. }
  79798. this.onTasksDoneObservable.notifyObservers(this._tasks);
  79799. }
  79800. catch (e) {
  79801. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  79802. console.log(e);
  79803. }
  79804. this._isLoading = false;
  79805. this._scene.getEngine().hideLoadingUI();
  79806. }
  79807. };
  79808. AssetsManager.prototype._runTask = function (task) {
  79809. var _this = this;
  79810. var done = function () {
  79811. try {
  79812. if (_this.onTaskSuccess) {
  79813. _this.onTaskSuccess(task);
  79814. }
  79815. _this.onTaskSuccessObservable.notifyObservers(task);
  79816. _this._decreaseWaitingTasksCount(task);
  79817. }
  79818. catch (e) {
  79819. error("Error executing task success callbacks", e);
  79820. }
  79821. };
  79822. var error = function (message, exception) {
  79823. task._setErrorObject(message, exception);
  79824. if (_this.onTaskError) {
  79825. _this.onTaskError(task);
  79826. }
  79827. _this.onTaskErrorObservable.notifyObservers(task);
  79828. _this._decreaseWaitingTasksCount(task);
  79829. };
  79830. task.run(this._scene, done, error);
  79831. };
  79832. /**
  79833. * Reset the {BABYLON.AssetsManager} and remove all tasks
  79834. * @return the current instance of the {BABYLON.AssetsManager}
  79835. */
  79836. AssetsManager.prototype.reset = function () {
  79837. this._isLoading = false;
  79838. this._tasks = new Array();
  79839. return this;
  79840. };
  79841. /**
  79842. * Start the loading process
  79843. * @return the current instance of the {BABYLON.AssetsManager}
  79844. */
  79845. AssetsManager.prototype.load = function () {
  79846. if (this._isLoading) {
  79847. return this;
  79848. }
  79849. this._isLoading = true;
  79850. this._waitingTasksCount = this._tasks.length;
  79851. this._totalTasksCount = this._tasks.length;
  79852. if (this._waitingTasksCount === 0) {
  79853. if (this.onFinish) {
  79854. this.onFinish(this._tasks);
  79855. }
  79856. this.onTasksDoneObservable.notifyObservers(this._tasks);
  79857. return this;
  79858. }
  79859. if (this.useDefaultLoadingScreen) {
  79860. this._scene.getEngine().displayLoadingUI();
  79861. }
  79862. for (var index = 0; index < this._tasks.length; index++) {
  79863. var task = this._tasks[index];
  79864. this._runTask(task);
  79865. }
  79866. return this;
  79867. };
  79868. return AssetsManager;
  79869. }());
  79870. BABYLON.AssetsManager = AssetsManager;
  79871. })(BABYLON || (BABYLON = {}));
  79872. //# sourceMappingURL=babylon.assetsManager.js.map
  79873. var BABYLON;
  79874. (function (BABYLON) {
  79875. var serializedGeometries = [];
  79876. var serializeGeometry = function (geometry, serializationGeometries) {
  79877. if (serializedGeometries[geometry.id]) {
  79878. return;
  79879. }
  79880. if (geometry.doNotSerialize) {
  79881. return;
  79882. }
  79883. if (geometry instanceof BABYLON.BoxGeometry) {
  79884. serializationGeometries.boxes.push(geometry.serialize());
  79885. }
  79886. else if (geometry instanceof BABYLON.SphereGeometry) {
  79887. serializationGeometries.spheres.push(geometry.serialize());
  79888. }
  79889. else if (geometry instanceof BABYLON.CylinderGeometry) {
  79890. serializationGeometries.cylinders.push(geometry.serialize());
  79891. }
  79892. else if (geometry instanceof BABYLON.TorusGeometry) {
  79893. serializationGeometries.toruses.push(geometry.serialize());
  79894. }
  79895. else if (geometry instanceof BABYLON.GroundGeometry) {
  79896. serializationGeometries.grounds.push(geometry.serialize());
  79897. }
  79898. else if (geometry instanceof BABYLON.Plane) {
  79899. serializationGeometries.planes.push(geometry.serialize());
  79900. }
  79901. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  79902. serializationGeometries.torusKnots.push(geometry.serialize());
  79903. }
  79904. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  79905. throw new Error("Unknown primitive type");
  79906. }
  79907. else {
  79908. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  79909. }
  79910. serializedGeometries[geometry.id] = true;
  79911. };
  79912. var serializeMesh = function (mesh, serializationScene) {
  79913. var serializationObject = {};
  79914. // Geometry
  79915. var geometry = mesh._geometry;
  79916. if (geometry) {
  79917. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  79918. // 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
  79919. serializeGeometry(geometry, serializationScene.geometries);
  79920. }
  79921. }
  79922. // Custom
  79923. if (mesh.serialize) {
  79924. mesh.serialize(serializationObject);
  79925. }
  79926. return serializationObject;
  79927. };
  79928. var finalizeSingleMesh = function (mesh, serializationObject) {
  79929. //only works if the mesh is already loaded
  79930. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  79931. //serialize material
  79932. if (mesh.material) {
  79933. if (mesh.material instanceof BABYLON.StandardMaterial) {
  79934. serializationObject.materials = serializationObject.materials || [];
  79935. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  79936. serializationObject.materials.push(mesh.material.serialize());
  79937. }
  79938. }
  79939. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  79940. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  79941. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  79942. serializationObject.multiMaterials.push(mesh.material.serialize());
  79943. }
  79944. }
  79945. }
  79946. //serialize geometry
  79947. var geometry = mesh._geometry;
  79948. if (geometry) {
  79949. if (!serializationObject.geometries) {
  79950. serializationObject.geometries = {};
  79951. serializationObject.geometries.boxes = [];
  79952. serializationObject.geometries.spheres = [];
  79953. serializationObject.geometries.cylinders = [];
  79954. serializationObject.geometries.toruses = [];
  79955. serializationObject.geometries.grounds = [];
  79956. serializationObject.geometries.planes = [];
  79957. serializationObject.geometries.torusKnots = [];
  79958. serializationObject.geometries.vertexData = [];
  79959. }
  79960. serializeGeometry(geometry, serializationObject.geometries);
  79961. }
  79962. // Skeletons
  79963. if (mesh.skeleton) {
  79964. serializationObject.skeletons = serializationObject.skeletons || [];
  79965. serializationObject.skeletons.push(mesh.skeleton.serialize());
  79966. }
  79967. //serialize the actual mesh
  79968. serializationObject.meshes = serializationObject.meshes || [];
  79969. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  79970. }
  79971. };
  79972. var SceneSerializer = /** @class */ (function () {
  79973. function SceneSerializer() {
  79974. }
  79975. SceneSerializer.ClearCache = function () {
  79976. serializedGeometries = [];
  79977. };
  79978. SceneSerializer.Serialize = function (scene) {
  79979. var serializationObject = {};
  79980. SceneSerializer.ClearCache();
  79981. // Scene
  79982. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  79983. serializationObject.autoClear = scene.autoClear;
  79984. serializationObject.clearColor = scene.clearColor.asArray();
  79985. serializationObject.ambientColor = scene.ambientColor.asArray();
  79986. serializationObject.gravity = scene.gravity.asArray();
  79987. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  79988. serializationObject.workerCollisions = scene.workerCollisions;
  79989. // Fog
  79990. if (scene.fogMode && scene.fogMode !== 0) {
  79991. serializationObject.fogMode = scene.fogMode;
  79992. serializationObject.fogColor = scene.fogColor.asArray();
  79993. serializationObject.fogStart = scene.fogStart;
  79994. serializationObject.fogEnd = scene.fogEnd;
  79995. serializationObject.fogDensity = scene.fogDensity;
  79996. }
  79997. //Physics
  79998. if (scene.isPhysicsEnabled()) {
  79999. var physicEngine = scene.getPhysicsEngine();
  80000. if (physicEngine) {
  80001. serializationObject.physicsEnabled = true;
  80002. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80003. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80004. }
  80005. }
  80006. // Metadata
  80007. if (scene.metadata) {
  80008. serializationObject.metadata = scene.metadata;
  80009. }
  80010. // Morph targets
  80011. serializationObject.morphTargetManagers = [];
  80012. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80013. var abstractMesh = _a[_i];
  80014. var manager = abstractMesh.morphTargetManager;
  80015. if (manager) {
  80016. serializationObject.morphTargetManagers.push(manager.serialize());
  80017. }
  80018. }
  80019. // Lights
  80020. serializationObject.lights = [];
  80021. var index;
  80022. var light;
  80023. for (index = 0; index < scene.lights.length; index++) {
  80024. light = scene.lights[index];
  80025. if (!light.doNotSerialize) {
  80026. serializationObject.lights.push(light.serialize());
  80027. }
  80028. }
  80029. // Cameras
  80030. serializationObject.cameras = [];
  80031. for (index = 0; index < scene.cameras.length; index++) {
  80032. var camera = scene.cameras[index];
  80033. if (!camera.doNotSerialize) {
  80034. serializationObject.cameras.push(camera.serialize());
  80035. }
  80036. }
  80037. if (scene.activeCamera) {
  80038. serializationObject.activeCameraID = scene.activeCamera.id;
  80039. }
  80040. // Animations
  80041. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80042. // Materials
  80043. serializationObject.materials = [];
  80044. serializationObject.multiMaterials = [];
  80045. var material;
  80046. for (index = 0; index < scene.materials.length; index++) {
  80047. material = scene.materials[index];
  80048. if (!material.doNotSerialize) {
  80049. serializationObject.materials.push(material.serialize());
  80050. }
  80051. }
  80052. // MultiMaterials
  80053. serializationObject.multiMaterials = [];
  80054. for (index = 0; index < scene.multiMaterials.length; index++) {
  80055. var multiMaterial = scene.multiMaterials[index];
  80056. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80057. }
  80058. // Environment texture
  80059. if (scene.environmentTexture) {
  80060. serializationObject.environmentTexture = scene.environmentTexture.name;
  80061. }
  80062. // Skeletons
  80063. serializationObject.skeletons = [];
  80064. for (index = 0; index < scene.skeletons.length; index++) {
  80065. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80066. }
  80067. // Transform nodes
  80068. serializationObject.transformNodes = [];
  80069. for (index = 0; index < scene.transformNodes.length; index++) {
  80070. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80071. }
  80072. // Geometries
  80073. serializationObject.geometries = {};
  80074. serializationObject.geometries.boxes = [];
  80075. serializationObject.geometries.spheres = [];
  80076. serializationObject.geometries.cylinders = [];
  80077. serializationObject.geometries.toruses = [];
  80078. serializationObject.geometries.grounds = [];
  80079. serializationObject.geometries.planes = [];
  80080. serializationObject.geometries.torusKnots = [];
  80081. serializationObject.geometries.vertexData = [];
  80082. serializedGeometries = [];
  80083. var geometries = scene.getGeometries();
  80084. for (index = 0; index < geometries.length; index++) {
  80085. var geometry = geometries[index];
  80086. if (geometry.isReady()) {
  80087. serializeGeometry(geometry, serializationObject.geometries);
  80088. }
  80089. }
  80090. // Meshes
  80091. serializationObject.meshes = [];
  80092. for (index = 0; index < scene.meshes.length; index++) {
  80093. var abstractMesh = scene.meshes[index];
  80094. if (abstractMesh instanceof BABYLON.Mesh) {
  80095. var mesh = abstractMesh;
  80096. if (!mesh.doNotSerialize) {
  80097. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80098. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80099. }
  80100. }
  80101. }
  80102. }
  80103. // Particles Systems
  80104. serializationObject.particleSystems = [];
  80105. for (index = 0; index < scene.particleSystems.length; index++) {
  80106. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80107. }
  80108. // Lens flares
  80109. serializationObject.lensFlareSystems = [];
  80110. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80111. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80112. }
  80113. // Shadows
  80114. serializationObject.shadowGenerators = [];
  80115. for (index = 0; index < scene.lights.length; index++) {
  80116. light = scene.lights[index];
  80117. var shadowGenerator = light.getShadowGenerator();
  80118. if (shadowGenerator) {
  80119. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80120. }
  80121. }
  80122. // Action Manager
  80123. if (scene.actionManager) {
  80124. serializationObject.actions = scene.actionManager.serialize("scene");
  80125. }
  80126. // Audio
  80127. serializationObject.sounds = [];
  80128. for (index = 0; index < scene.soundTracks.length; index++) {
  80129. var soundtrack = scene.soundTracks[index];
  80130. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80131. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80132. }
  80133. }
  80134. return serializationObject;
  80135. };
  80136. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80137. if (withParents === void 0) { withParents = false; }
  80138. if (withChildren === void 0) { withChildren = false; }
  80139. var serializationObject = {};
  80140. SceneSerializer.ClearCache();
  80141. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80142. if (withParents || withChildren) {
  80143. //deliberate for loop! not for each, appended should be processed as well.
  80144. for (var i = 0; i < toSerialize.length; ++i) {
  80145. if (withChildren) {
  80146. toSerialize[i].getDescendants().forEach(function (node) {
  80147. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80148. toSerialize.push(node);
  80149. }
  80150. });
  80151. }
  80152. //make sure the array doesn't contain the object already
  80153. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80154. toSerialize.push(toSerialize[i].parent);
  80155. }
  80156. }
  80157. }
  80158. toSerialize.forEach(function (mesh) {
  80159. finalizeSingleMesh(mesh, serializationObject);
  80160. });
  80161. return serializationObject;
  80162. };
  80163. return SceneSerializer;
  80164. }());
  80165. BABYLON.SceneSerializer = SceneSerializer;
  80166. })(BABYLON || (BABYLON = {}));
  80167. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80168. var BABYLON;
  80169. (function (BABYLON) {
  80170. var ReflectionProbe = /** @class */ (function () {
  80171. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80173. var _this = this;
  80174. this.name = name;
  80175. this._viewMatrix = BABYLON.Matrix.Identity();
  80176. this._target = BABYLON.Vector3.Zero();
  80177. this._add = BABYLON.Vector3.Zero();
  80178. this.invertYAxis = false;
  80179. this.position = BABYLON.Vector3.Zero();
  80180. this._scene = scene;
  80181. this._scene.reflectionProbes.push(this);
  80182. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80183. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80184. switch (faceIndex) {
  80185. case 0:
  80186. _this._add.copyFromFloats(1, 0, 0);
  80187. break;
  80188. case 1:
  80189. _this._add.copyFromFloats(-1, 0, 0);
  80190. break;
  80191. case 2:
  80192. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80193. break;
  80194. case 3:
  80195. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80196. break;
  80197. case 4:
  80198. _this._add.copyFromFloats(0, 0, 1);
  80199. break;
  80200. case 5:
  80201. _this._add.copyFromFloats(0, 0, -1);
  80202. break;
  80203. }
  80204. if (_this._attachedMesh) {
  80205. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80206. }
  80207. _this.position.addToRef(_this._add, _this._target);
  80208. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80209. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80210. scene._forcedViewPosition = _this.position;
  80211. });
  80212. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80213. scene._forcedViewPosition = null;
  80214. scene.updateTransformMatrix(true);
  80215. });
  80216. if (scene.activeCamera) {
  80217. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80218. }
  80219. }
  80220. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80221. get: function () {
  80222. return this._renderTargetTexture.samples;
  80223. },
  80224. set: function (value) {
  80225. this._renderTargetTexture.samples = value;
  80226. },
  80227. enumerable: true,
  80228. configurable: true
  80229. });
  80230. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80231. get: function () {
  80232. return this._renderTargetTexture.refreshRate;
  80233. },
  80234. set: function (value) {
  80235. this._renderTargetTexture.refreshRate = value;
  80236. },
  80237. enumerable: true,
  80238. configurable: true
  80239. });
  80240. ReflectionProbe.prototype.getScene = function () {
  80241. return this._scene;
  80242. };
  80243. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80244. get: function () {
  80245. return this._renderTargetTexture;
  80246. },
  80247. enumerable: true,
  80248. configurable: true
  80249. });
  80250. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80251. get: function () {
  80252. return this._renderTargetTexture.renderList;
  80253. },
  80254. enumerable: true,
  80255. configurable: true
  80256. });
  80257. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80258. this._attachedMesh = mesh;
  80259. };
  80260. /**
  80261. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80262. *
  80263. * @param renderingGroupId The rendering group id corresponding to its index
  80264. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80265. */
  80266. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80267. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80268. };
  80269. ReflectionProbe.prototype.dispose = function () {
  80270. var index = this._scene.reflectionProbes.indexOf(this);
  80271. if (index !== -1) {
  80272. // Remove from the scene if found
  80273. this._scene.reflectionProbes.splice(index, 1);
  80274. }
  80275. if (this._renderTargetTexture) {
  80276. this._renderTargetTexture.dispose();
  80277. this._renderTargetTexture = null;
  80278. }
  80279. };
  80280. return ReflectionProbe;
  80281. }());
  80282. BABYLON.ReflectionProbe = ReflectionProbe;
  80283. })(BABYLON || (BABYLON = {}));
  80284. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80285. var BABYLON;
  80286. (function (BABYLON) {
  80287. var Layer = /** @class */ (function () {
  80288. function Layer(name, imgUrl, scene, isBackground, color) {
  80289. this.name = name;
  80290. this.scale = new BABYLON.Vector2(1, 1);
  80291. this.offset = new BABYLON.Vector2(0, 0);
  80292. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  80293. this.layerMask = 0x0FFFFFFF;
  80294. this._vertexBuffers = {};
  80295. // Events
  80296. /**
  80297. * An event triggered when the layer is disposed.
  80298. * @type {BABYLON.Observable}
  80299. */
  80300. this.onDisposeObservable = new BABYLON.Observable();
  80301. /**
  80302. * An event triggered before rendering the scene
  80303. * @type {BABYLON.Observable}
  80304. */
  80305. this.onBeforeRenderObservable = new BABYLON.Observable();
  80306. /**
  80307. * An event triggered after rendering the scene
  80308. * @type {BABYLON.Observable}
  80309. */
  80310. this.onAfterRenderObservable = new BABYLON.Observable();
  80311. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  80312. this.isBackground = isBackground === undefined ? true : isBackground;
  80313. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  80314. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  80315. this._scene.layers.push(this);
  80316. var engine = this._scene.getEngine();
  80317. // VBO
  80318. var vertices = [];
  80319. vertices.push(1, 1);
  80320. vertices.push(-1, 1);
  80321. vertices.push(-1, -1);
  80322. vertices.push(1, -1);
  80323. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80324. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80325. this._createIndexBuffer();
  80326. // Effects
  80327. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  80328. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  80329. }
  80330. Object.defineProperty(Layer.prototype, "onDispose", {
  80331. set: function (callback) {
  80332. if (this._onDisposeObserver) {
  80333. this.onDisposeObservable.remove(this._onDisposeObserver);
  80334. }
  80335. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  80336. },
  80337. enumerable: true,
  80338. configurable: true
  80339. });
  80340. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  80341. set: function (callback) {
  80342. if (this._onBeforeRenderObserver) {
  80343. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  80344. }
  80345. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  80346. },
  80347. enumerable: true,
  80348. configurable: true
  80349. });
  80350. Object.defineProperty(Layer.prototype, "onAfterRender", {
  80351. set: function (callback) {
  80352. if (this._onAfterRenderObserver) {
  80353. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80354. }
  80355. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  80356. },
  80357. enumerable: true,
  80358. configurable: true
  80359. });
  80360. Layer.prototype._createIndexBuffer = function () {
  80361. var engine = this._scene.getEngine();
  80362. // Indices
  80363. var indices = [];
  80364. indices.push(0);
  80365. indices.push(1);
  80366. indices.push(2);
  80367. indices.push(0);
  80368. indices.push(2);
  80369. indices.push(3);
  80370. this._indexBuffer = engine.createIndexBuffer(indices);
  80371. };
  80372. Layer.prototype._rebuild = function () {
  80373. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80374. if (vb) {
  80375. vb._rebuild();
  80376. }
  80377. this._createIndexBuffer();
  80378. };
  80379. Layer.prototype.render = function () {
  80380. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  80381. // Check
  80382. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  80383. return;
  80384. var engine = this._scene.getEngine();
  80385. this.onBeforeRenderObservable.notifyObservers(this);
  80386. // Render
  80387. engine.enableEffect(currentEffect);
  80388. engine.setState(false);
  80389. // Texture
  80390. currentEffect.setTexture("textureSampler", this.texture);
  80391. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  80392. // Color
  80393. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  80394. // Scale / offset
  80395. currentEffect.setVector2("offset", this.offset);
  80396. currentEffect.setVector2("scale", this.scale);
  80397. // VBOs
  80398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80399. // Draw order
  80400. if (!this.alphaTest) {
  80401. engine.setAlphaMode(this.alphaBlendingMode);
  80402. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80404. }
  80405. else {
  80406. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80407. }
  80408. this.onAfterRenderObservable.notifyObservers(this);
  80409. };
  80410. Layer.prototype.dispose = function () {
  80411. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80412. if (vertexBuffer) {
  80413. vertexBuffer.dispose();
  80414. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80415. }
  80416. if (this._indexBuffer) {
  80417. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80418. this._indexBuffer = null;
  80419. }
  80420. if (this.texture) {
  80421. this.texture.dispose();
  80422. this.texture = null;
  80423. }
  80424. // Remove from scene
  80425. var index = this._scene.layers.indexOf(this);
  80426. this._scene.layers.splice(index, 1);
  80427. // Callback
  80428. this.onDisposeObservable.notifyObservers(this);
  80429. this.onDisposeObservable.clear();
  80430. this.onAfterRenderObservable.clear();
  80431. this.onBeforeRenderObservable.clear();
  80432. };
  80433. return Layer;
  80434. }());
  80435. BABYLON.Layer = Layer;
  80436. })(BABYLON || (BABYLON = {}));
  80437. //# sourceMappingURL=babylon.layer.js.map
  80438. var BABYLON;
  80439. (function (BABYLON) {
  80440. var TextureTools = /** @class */ (function () {
  80441. function TextureTools() {
  80442. }
  80443. /**
  80444. * Uses the GPU to create a copy texture rescaled at a given size
  80445. * @param texture Texture to copy from
  80446. * @param width Desired width
  80447. * @param height Desired height
  80448. * @return Generated texture
  80449. */
  80450. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  80451. if (useBilinearMode === void 0) { useBilinearMode = true; }
  80452. var scene = texture.getScene();
  80453. var engine = scene.getEngine();
  80454. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  80455. rtt.wrapU = texture.wrapU;
  80456. rtt.wrapV = texture.wrapV;
  80457. rtt.uOffset = texture.uOffset;
  80458. rtt.vOffset = texture.vOffset;
  80459. rtt.uScale = texture.uScale;
  80460. rtt.vScale = texture.vScale;
  80461. rtt.uAng = texture.uAng;
  80462. rtt.vAng = texture.vAng;
  80463. rtt.wAng = texture.wAng;
  80464. rtt.coordinatesIndex = texture.coordinatesIndex;
  80465. rtt.level = texture.level;
  80466. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  80467. rtt._texture.isReady = false;
  80468. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80469. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80470. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80471. passPostProcess.getEffect().executeWhenCompiled(function () {
  80472. passPostProcess.onApply = function (effect) {
  80473. effect.setTexture("textureSampler", texture);
  80474. };
  80475. var internalTexture = rtt.getInternalTexture();
  80476. if (internalTexture) {
  80477. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  80478. engine.unBindFramebuffer(internalTexture);
  80479. rtt.disposeFramebufferObjects();
  80480. passPostProcess.dispose();
  80481. internalTexture.isReady = true;
  80482. }
  80483. });
  80484. return rtt;
  80485. };
  80486. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  80487. if (!scene._environmentBRDFTexture) {
  80488. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80489. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80490. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80491. scene._environmentBRDFTexture = texture;
  80492. }
  80493. return scene._environmentBRDFTexture;
  80494. };
  80495. 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=";
  80496. return TextureTools;
  80497. }());
  80498. BABYLON.TextureTools = TextureTools;
  80499. })(BABYLON || (BABYLON = {}));
  80500. //# sourceMappingURL=babylon.textureTools.js.map
  80501. var BABYLON;
  80502. (function (BABYLON) {
  80503. var FramingBehavior = /** @class */ (function () {
  80504. function FramingBehavior() {
  80505. this._mode = FramingBehavior.FitFrustumSidesMode;
  80506. this._radiusScale = 1.0;
  80507. this._positionScale = 0.5;
  80508. this._defaultElevation = 0.3;
  80509. this._elevationReturnTime = 1500;
  80510. this._elevationReturnWaitTime = 1000;
  80511. this._zoomStopsAnimation = false;
  80512. this._framingTime = 1500;
  80513. this._isPointerDown = false;
  80514. this._lastInteractionTime = -Infinity;
  80515. // Framing control
  80516. this._animatables = new Array();
  80517. this._betaIsAnimating = false;
  80518. }
  80519. Object.defineProperty(FramingBehavior.prototype, "name", {
  80520. get: function () {
  80521. return "Framing";
  80522. },
  80523. enumerable: true,
  80524. configurable: true
  80525. });
  80526. Object.defineProperty(FramingBehavior.prototype, "mode", {
  80527. /**
  80528. * Gets current mode used by the behavior.
  80529. */
  80530. get: function () {
  80531. return this._mode;
  80532. },
  80533. /**
  80534. * Sets the current mode used by the behavior
  80535. */
  80536. set: function (mode) {
  80537. this._mode = mode;
  80538. },
  80539. enumerable: true,
  80540. configurable: true
  80541. });
  80542. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  80543. /**
  80544. * Gets the scale applied to the radius
  80545. */
  80546. get: function () {
  80547. return this._radiusScale;
  80548. },
  80549. /**
  80550. * Sets the scale applied to the radius (1 by default)
  80551. */
  80552. set: function (radius) {
  80553. this._radiusScale = radius;
  80554. },
  80555. enumerable: true,
  80556. configurable: true
  80557. });
  80558. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  80559. /**
  80560. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80561. */
  80562. get: function () {
  80563. return this._positionScale;
  80564. },
  80565. /**
  80566. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80567. */
  80568. set: function (scale) {
  80569. this._positionScale = scale;
  80570. },
  80571. enumerable: true,
  80572. configurable: true
  80573. });
  80574. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  80575. /**
  80576. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80577. * behaviour is triggered, in radians.
  80578. */
  80579. get: function () {
  80580. return this._defaultElevation;
  80581. },
  80582. /**
  80583. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80584. * behaviour is triggered, in radians.
  80585. */
  80586. set: function (elevation) {
  80587. this._defaultElevation = elevation;
  80588. },
  80589. enumerable: true,
  80590. configurable: true
  80591. });
  80592. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  80593. /**
  80594. * Gets the time (in milliseconds) taken to return to the default beta position.
  80595. * Negative value indicates camera should not return to default.
  80596. */
  80597. get: function () {
  80598. return this._elevationReturnTime;
  80599. },
  80600. /**
  80601. * Sets the time (in milliseconds) taken to return to the default beta position.
  80602. * Negative value indicates camera should not return to default.
  80603. */
  80604. set: function (speed) {
  80605. this._elevationReturnTime = speed;
  80606. },
  80607. enumerable: true,
  80608. configurable: true
  80609. });
  80610. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  80611. /**
  80612. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80613. */
  80614. get: function () {
  80615. return this._elevationReturnWaitTime;
  80616. },
  80617. /**
  80618. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80619. */
  80620. set: function (time) {
  80621. this._elevationReturnWaitTime = time;
  80622. },
  80623. enumerable: true,
  80624. configurable: true
  80625. });
  80626. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  80627. /**
  80628. * Gets the flag that indicates if user zooming should stop animation.
  80629. */
  80630. get: function () {
  80631. return this._zoomStopsAnimation;
  80632. },
  80633. /**
  80634. * Sets the flag that indicates if user zooming should stop animation.
  80635. */
  80636. set: function (flag) {
  80637. this._zoomStopsAnimation = flag;
  80638. },
  80639. enumerable: true,
  80640. configurable: true
  80641. });
  80642. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  80643. /**
  80644. * Gets the transition time when framing the mesh, in milliseconds
  80645. */
  80646. get: function () {
  80647. return this._framingTime;
  80648. },
  80649. /**
  80650. * Sets the transition time when framing the mesh, in milliseconds
  80651. */
  80652. set: function (time) {
  80653. this._framingTime = time;
  80654. },
  80655. enumerable: true,
  80656. configurable: true
  80657. });
  80658. FramingBehavior.prototype.init = function () {
  80659. // Do notihng
  80660. };
  80661. FramingBehavior.prototype.attach = function (camera) {
  80662. var _this = this;
  80663. this._attachedCamera = camera;
  80664. var scene = this._attachedCamera.getScene();
  80665. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  80666. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  80667. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80668. _this._isPointerDown = true;
  80669. return;
  80670. }
  80671. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  80672. _this._isPointerDown = false;
  80673. }
  80674. });
  80675. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  80676. if (mesh) {
  80677. _this.zoomOnMesh(mesh);
  80678. }
  80679. });
  80680. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  80681. // Stop the animation if there is user interaction and the animation should stop for this interaction
  80682. _this._applyUserInteraction();
  80683. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  80684. // back to the default position after a given timeout
  80685. _this._maintainCameraAboveGround();
  80686. });
  80687. };
  80688. FramingBehavior.prototype.detach = function () {
  80689. if (!this._attachedCamera) {
  80690. return;
  80691. }
  80692. var scene = this._attachedCamera.getScene();
  80693. if (this._onPrePointerObservableObserver) {
  80694. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  80695. }
  80696. if (this._onAfterCheckInputsObserver) {
  80697. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  80698. }
  80699. if (this._onMeshTargetChangedObserver) {
  80700. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  80701. }
  80702. this._attachedCamera = null;
  80703. };
  80704. /**
  80705. * Targets the given mesh and updates zoom level accordingly.
  80706. * @param mesh The mesh to target.
  80707. * @param radius Optional. If a cached radius position already exists, overrides default.
  80708. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80709. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80710. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80711. */
  80712. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  80713. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80714. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80715. mesh.computeWorldMatrix(true);
  80716. var boundingBox = mesh.getBoundingInfo().boundingBox;
  80717. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  80718. };
  80719. /**
  80720. * Targets the given mesh with its children and updates zoom level accordingly.
  80721. * @param mesh The mesh to target.
  80722. * @param radius Optional. If a cached radius position already exists, overrides default.
  80723. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80724. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80725. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80726. */
  80727. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  80728. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80729. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80730. mesh.computeWorldMatrix(true);
  80731. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  80732. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  80733. };
  80734. /**
  80735. * Targets the given meshes with their children and updates zoom level accordingly.
  80736. * @param meshes The mesh to target.
  80737. * @param radius Optional. If a cached radius position already exists, overrides default.
  80738. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80739. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80740. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80741. */
  80742. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  80743. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80744. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80745. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  80746. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  80747. for (var i = 0; i < meshes.length; i++) {
  80748. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  80749. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  80750. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  80751. }
  80752. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  80753. };
  80754. /**
  80755. * Targets the given mesh and updates zoom level accordingly.
  80756. * @param mesh The mesh to target.
  80757. * @param radius Optional. If a cached radius position already exists, overrides default.
  80758. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80759. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80760. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80761. */
  80762. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  80763. var _this = this;
  80764. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80765. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80766. var zoomTarget;
  80767. if (!this._attachedCamera) {
  80768. return;
  80769. }
  80770. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  80771. var bottom = minimumWorld.y;
  80772. var top = maximumWorld.y;
  80773. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  80774. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  80775. if (focusOnOriginXZ) {
  80776. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  80777. }
  80778. else {
  80779. var centerWorld = minimumWorld.add(radiusWorld);
  80780. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  80781. }
  80782. if (!this._vectorTransition) {
  80783. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  80784. }
  80785. this._betaIsAnimating = true;
  80786. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  80787. if (animatable) {
  80788. this._animatables.push(animatable);
  80789. }
  80790. // sets the radius and lower radius bounds
  80791. // Small delta ensures camera is not always at lower zoom limit.
  80792. var radius = 0;
  80793. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  80794. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  80795. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  80796. radius = position;
  80797. }
  80798. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  80799. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  80800. if (this._attachedCamera.lowerRadiusLimit === null) {
  80801. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  80802. }
  80803. }
  80804. // Set sensibilities
  80805. var extend = maximumWorld.subtract(minimumWorld).length();
  80806. this._attachedCamera.panningSensibility = 5000 / extend;
  80807. this._attachedCamera.wheelPrecision = 100 / radius;
  80808. // transition to new radius
  80809. if (!this._radiusTransition) {
  80810. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  80811. }
  80812. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  80813. if (onAnimationEnd) {
  80814. onAnimationEnd();
  80815. }
  80816. if (_this._attachedCamera) {
  80817. _this._attachedCamera.storeState();
  80818. }
  80819. });
  80820. if (animatable) {
  80821. this._animatables.push(animatable);
  80822. }
  80823. };
  80824. /**
  80825. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  80826. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  80827. * frustum width.
  80828. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  80829. * to fully enclose the mesh in the viewing frustum.
  80830. */
  80831. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  80832. var size = maximumWorld.subtract(minimumWorld);
  80833. var boxVectorGlobalDiagonal = size.length();
  80834. var frustumSlope = this._getFrustumSlope();
  80835. // Formula for setting distance
  80836. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  80837. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  80838. // Horizon distance
  80839. var radius = radiusWithoutFraming * this._radiusScale;
  80840. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  80841. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  80842. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  80843. var camera = this._attachedCamera;
  80844. if (!camera) {
  80845. return 0;
  80846. }
  80847. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  80848. // Don't exceed the requested limit
  80849. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  80850. }
  80851. // Don't exceed the upper radius limit
  80852. if (camera.upperRadiusLimit) {
  80853. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  80854. }
  80855. return distance;
  80856. };
  80857. /**
  80858. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  80859. * is automatically returned to its default position (expected to be above ground plane).
  80860. */
  80861. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  80862. var _this = this;
  80863. if (this._elevationReturnTime < 0) {
  80864. return;
  80865. }
  80866. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  80867. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  80868. var limitBeta = Math.PI * 0.5;
  80869. // Bring the camera back up if below the ground plane
  80870. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  80871. this._betaIsAnimating = true;
  80872. //Transition to new position
  80873. this.stopAllAnimations();
  80874. if (!this._betaTransition) {
  80875. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  80876. }
  80877. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  80878. _this._clearAnimationLocks();
  80879. _this.stopAllAnimations();
  80880. });
  80881. if (animatabe) {
  80882. this._animatables.push(animatabe);
  80883. }
  80884. }
  80885. };
  80886. /**
  80887. * Returns the frustum slope based on the canvas ratio and camera FOV
  80888. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  80889. */
  80890. FramingBehavior.prototype._getFrustumSlope = function () {
  80891. // Calculate the viewport ratio
  80892. // Aspect Ratio is Height/Width.
  80893. var camera = this._attachedCamera;
  80894. if (!camera) {
  80895. return BABYLON.Vector2.Zero();
  80896. }
  80897. var engine = camera.getScene().getEngine();
  80898. var aspectRatio = engine.getAspectRatio(camera);
  80899. // Camera FOV is the vertical field of view (top-bottom) in radians.
  80900. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  80901. var frustumSlopeY = Math.tan(camera.fov / 2);
  80902. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  80903. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  80904. // along the forward vector.
  80905. var frustumSlopeX = frustumSlopeY * aspectRatio;
  80906. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  80907. };
  80908. /**
  80909. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  80910. */
  80911. FramingBehavior.prototype._clearAnimationLocks = function () {
  80912. this._betaIsAnimating = false;
  80913. };
  80914. /**
  80915. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  80916. */
  80917. FramingBehavior.prototype._applyUserInteraction = function () {
  80918. if (this.isUserIsMoving) {
  80919. this._lastInteractionTime = BABYLON.Tools.Now;
  80920. this.stopAllAnimations();
  80921. this._clearAnimationLocks();
  80922. }
  80923. };
  80924. /**
  80925. * Stops and removes all animations that have been applied to the camera
  80926. */
  80927. FramingBehavior.prototype.stopAllAnimations = function () {
  80928. if (this._attachedCamera) {
  80929. this._attachedCamera.animations = [];
  80930. }
  80931. while (this._animatables.length) {
  80932. if (this._animatables[0]) {
  80933. this._animatables[0].onAnimationEnd = null;
  80934. this._animatables[0].stop();
  80935. }
  80936. this._animatables.shift();
  80937. }
  80938. };
  80939. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  80940. /**
  80941. * Gets a value indicating if the user is moving the camera
  80942. */
  80943. get: function () {
  80944. if (!this._attachedCamera) {
  80945. return false;
  80946. }
  80947. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  80948. this._attachedCamera.inertialBetaOffset !== 0 ||
  80949. this._attachedCamera.inertialRadiusOffset !== 0 ||
  80950. this._attachedCamera.inertialPanningX !== 0 ||
  80951. this._attachedCamera.inertialPanningY !== 0 ||
  80952. this._isPointerDown;
  80953. },
  80954. enumerable: true,
  80955. configurable: true
  80956. });
  80957. /**
  80958. * The easing function used by animations
  80959. */
  80960. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  80961. /**
  80962. * The easing mode used by animations
  80963. */
  80964. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  80965. // Statics
  80966. /**
  80967. * The camera can move all the way towards the mesh.
  80968. */
  80969. FramingBehavior.IgnoreBoundsSizeMode = 0;
  80970. /**
  80971. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  80972. */
  80973. FramingBehavior.FitFrustumSidesMode = 1;
  80974. return FramingBehavior;
  80975. }());
  80976. BABYLON.FramingBehavior = FramingBehavior;
  80977. })(BABYLON || (BABYLON = {}));
  80978. //# sourceMappingURL=babylon.framingBehavior.js.map
  80979. var BABYLON;
  80980. (function (BABYLON) {
  80981. /**
  80982. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  80983. */
  80984. var BouncingBehavior = /** @class */ (function () {
  80985. function BouncingBehavior() {
  80986. /**
  80987. * The duration of the animation, in milliseconds
  80988. */
  80989. this.transitionDuration = 450;
  80990. /**
  80991. * Length of the distance animated by the transition when lower radius is reached
  80992. */
  80993. this.lowerRadiusTransitionRange = 2;
  80994. /**
  80995. * Length of the distance animated by the transition when upper radius is reached
  80996. */
  80997. this.upperRadiusTransitionRange = -2;
  80998. this._autoTransitionRange = false;
  80999. // Animations
  81000. this._radiusIsAnimating = false;
  81001. this._radiusBounceTransition = null;
  81002. this._animatables = new Array();
  81003. }
  81004. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81005. get: function () {
  81006. return "Bouncing";
  81007. },
  81008. enumerable: true,
  81009. configurable: true
  81010. });
  81011. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81012. /**
  81013. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81014. */
  81015. get: function () {
  81016. return this._autoTransitionRange;
  81017. },
  81018. /**
  81019. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81020. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81021. */
  81022. set: function (value) {
  81023. var _this = this;
  81024. if (this._autoTransitionRange === value) {
  81025. return;
  81026. }
  81027. this._autoTransitionRange = value;
  81028. var camera = this._attachedCamera;
  81029. if (!camera) {
  81030. return;
  81031. }
  81032. if (value) {
  81033. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81034. if (!mesh) {
  81035. return;
  81036. }
  81037. mesh.computeWorldMatrix(true);
  81038. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81039. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81040. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81041. });
  81042. }
  81043. else if (this._onMeshTargetChangedObserver) {
  81044. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81045. }
  81046. },
  81047. enumerable: true,
  81048. configurable: true
  81049. });
  81050. BouncingBehavior.prototype.init = function () {
  81051. // Do notihng
  81052. };
  81053. BouncingBehavior.prototype.attach = function (camera) {
  81054. var _this = this;
  81055. this._attachedCamera = camera;
  81056. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81057. if (!_this._attachedCamera) {
  81058. return;
  81059. }
  81060. // Add the bounce animation to the lower radius limit
  81061. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81062. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81063. }
  81064. // Add the bounce animation to the upper radius limit
  81065. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81066. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81067. }
  81068. });
  81069. };
  81070. BouncingBehavior.prototype.detach = function () {
  81071. if (!this._attachedCamera) {
  81072. return;
  81073. }
  81074. if (this._onAfterCheckInputsObserver) {
  81075. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81076. }
  81077. if (this._onMeshTargetChangedObserver) {
  81078. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81079. }
  81080. this._attachedCamera = null;
  81081. };
  81082. /**
  81083. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81084. * @param radiusLimit The limit to check against.
  81085. * @return Bool to indicate if at limit.
  81086. */
  81087. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81088. if (!this._attachedCamera) {
  81089. return false;
  81090. }
  81091. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81092. return true;
  81093. }
  81094. return false;
  81095. };
  81096. /**
  81097. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81098. * @param radiusDelta The delta by which to animate to. Can be negative.
  81099. */
  81100. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81101. var _this = this;
  81102. if (!this._attachedCamera) {
  81103. return;
  81104. }
  81105. if (!this._radiusBounceTransition) {
  81106. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81107. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81108. }
  81109. // Prevent zoom until bounce has completed
  81110. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81111. this._attachedCamera.wheelPrecision = Infinity;
  81112. this._attachedCamera.inertialRadiusOffset = 0;
  81113. // Animate to the radius limit
  81114. this.stopAllAnimations();
  81115. this._radiusIsAnimating = true;
  81116. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81117. if (animatable) {
  81118. this._animatables.push(animatable);
  81119. }
  81120. };
  81121. /**
  81122. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81123. */
  81124. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81125. this._radiusIsAnimating = false;
  81126. if (this._attachedCamera) {
  81127. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81128. }
  81129. };
  81130. /**
  81131. * Stops and removes all animations that have been applied to the camera
  81132. */
  81133. BouncingBehavior.prototype.stopAllAnimations = function () {
  81134. if (this._attachedCamera) {
  81135. this._attachedCamera.animations = [];
  81136. }
  81137. while (this._animatables.length) {
  81138. this._animatables[0].onAnimationEnd = null;
  81139. this._animatables[0].stop();
  81140. this._animatables.shift();
  81141. }
  81142. };
  81143. /**
  81144. * The easing function used by animations
  81145. */
  81146. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81147. /**
  81148. * The easing mode used by animations
  81149. */
  81150. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81151. return BouncingBehavior;
  81152. }());
  81153. BABYLON.BouncingBehavior = BouncingBehavior;
  81154. })(BABYLON || (BABYLON = {}));
  81155. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81156. var BABYLON;
  81157. (function (BABYLON) {
  81158. var AutoRotationBehavior = /** @class */ (function () {
  81159. function AutoRotationBehavior() {
  81160. this._zoomStopsAnimation = false;
  81161. this._idleRotationSpeed = 0.05;
  81162. this._idleRotationWaitTime = 2000;
  81163. this._idleRotationSpinupTime = 2000;
  81164. this._isPointerDown = false;
  81165. this._lastFrameTime = null;
  81166. this._lastInteractionTime = -Infinity;
  81167. this._cameraRotationSpeed = 0;
  81168. this._lastFrameRadius = 0;
  81169. }
  81170. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81171. get: function () {
  81172. return "AutoRotation";
  81173. },
  81174. enumerable: true,
  81175. configurable: true
  81176. });
  81177. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81178. /**
  81179. * Gets the flag that indicates if user zooming should stop animation.
  81180. */
  81181. get: function () {
  81182. return this._zoomStopsAnimation;
  81183. },
  81184. /**
  81185. * Sets the flag that indicates if user zooming should stop animation.
  81186. */
  81187. set: function (flag) {
  81188. this._zoomStopsAnimation = flag;
  81189. },
  81190. enumerable: true,
  81191. configurable: true
  81192. });
  81193. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81194. /**
  81195. * Gets the default speed at which the camera rotates around the model.
  81196. */
  81197. get: function () {
  81198. return this._idleRotationSpeed;
  81199. },
  81200. /**
  81201. * Sets the default speed at which the camera rotates around the model.
  81202. */
  81203. set: function (speed) {
  81204. this._idleRotationSpeed = speed;
  81205. },
  81206. enumerable: true,
  81207. configurable: true
  81208. });
  81209. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81210. /**
  81211. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81212. */
  81213. get: function () {
  81214. return this._idleRotationWaitTime;
  81215. },
  81216. /**
  81217. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81218. */
  81219. set: function (time) {
  81220. this._idleRotationWaitTime = time;
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81226. /**
  81227. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81228. */
  81229. get: function () {
  81230. return this._idleRotationSpinupTime;
  81231. },
  81232. /**
  81233. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81234. */
  81235. set: function (time) {
  81236. this._idleRotationSpinupTime = time;
  81237. },
  81238. enumerable: true,
  81239. configurable: true
  81240. });
  81241. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81242. /**
  81243. * Gets a value indicating if the camera is currently rotating because of this behavior
  81244. */
  81245. get: function () {
  81246. return Math.abs(this._cameraRotationSpeed) > 0;
  81247. },
  81248. enumerable: true,
  81249. configurable: true
  81250. });
  81251. AutoRotationBehavior.prototype.init = function () {
  81252. // Do notihng
  81253. };
  81254. AutoRotationBehavior.prototype.attach = function (camera) {
  81255. var _this = this;
  81256. this._attachedCamera = camera;
  81257. var scene = this._attachedCamera.getScene();
  81258. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81259. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81260. _this._isPointerDown = true;
  81261. return;
  81262. }
  81263. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81264. _this._isPointerDown = false;
  81265. }
  81266. });
  81267. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81268. var now = BABYLON.Tools.Now;
  81269. var dt = 0;
  81270. if (_this._lastFrameTime != null) {
  81271. dt = now - _this._lastFrameTime;
  81272. }
  81273. _this._lastFrameTime = now;
  81274. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81275. _this._applyUserInteraction();
  81276. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81277. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81278. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81279. // Step camera rotation by rotation speed
  81280. if (_this._attachedCamera) {
  81281. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81282. }
  81283. });
  81284. };
  81285. AutoRotationBehavior.prototype.detach = function () {
  81286. if (!this._attachedCamera) {
  81287. return;
  81288. }
  81289. var scene = this._attachedCamera.getScene();
  81290. if (this._onPrePointerObservableObserver) {
  81291. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81292. }
  81293. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81294. this._attachedCamera = null;
  81295. };
  81296. /**
  81297. * Returns true if user is scrolling.
  81298. * @return true if user is scrolling.
  81299. */
  81300. AutoRotationBehavior.prototype._userIsZooming = function () {
  81301. if (!this._attachedCamera) {
  81302. return false;
  81303. }
  81304. return this._attachedCamera.inertialRadiusOffset !== 0;
  81305. };
  81306. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  81307. if (!this._attachedCamera) {
  81308. return false;
  81309. }
  81310. var zoomHasHitLimit = false;
  81311. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  81312. zoomHasHitLimit = true;
  81313. }
  81314. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  81315. this._lastFrameRadius = this._attachedCamera.radius;
  81316. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  81317. };
  81318. /**
  81319. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81320. */
  81321. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  81322. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  81323. this._lastInteractionTime = BABYLON.Tools.Now;
  81324. }
  81325. };
  81326. // Tools
  81327. AutoRotationBehavior.prototype._userIsMoving = function () {
  81328. if (!this._attachedCamera) {
  81329. return false;
  81330. }
  81331. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81332. this._attachedCamera.inertialBetaOffset !== 0 ||
  81333. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81334. this._attachedCamera.inertialPanningX !== 0 ||
  81335. this._attachedCamera.inertialPanningY !== 0 ||
  81336. this._isPointerDown;
  81337. };
  81338. return AutoRotationBehavior;
  81339. }());
  81340. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  81341. })(BABYLON || (BABYLON = {}));
  81342. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  81343. var BABYLON;
  81344. (function (BABYLON) {
  81345. var NullEngineOptions = /** @class */ (function () {
  81346. function NullEngineOptions() {
  81347. this.renderWidth = 512;
  81348. this.renderHeight = 256;
  81349. this.textureSize = 512;
  81350. this.deterministicLockstep = false;
  81351. this.lockstepMaxSteps = 4;
  81352. }
  81353. return NullEngineOptions;
  81354. }());
  81355. BABYLON.NullEngineOptions = NullEngineOptions;
  81356. /**
  81357. * The null engine class provides support for headless version of babylon.js.
  81358. * This can be used in server side scenario or for testing purposes
  81359. */
  81360. var NullEngine = /** @class */ (function (_super) {
  81361. __extends(NullEngine, _super);
  81362. function NullEngine(options) {
  81363. if (options === void 0) { options = new NullEngineOptions(); }
  81364. var _this = _super.call(this, null) || this;
  81365. if (options.deterministicLockstep === undefined) {
  81366. options.deterministicLockstep = false;
  81367. }
  81368. if (options.lockstepMaxSteps === undefined) {
  81369. options.lockstepMaxSteps = 4;
  81370. }
  81371. _this._options = options;
  81372. // Init caps
  81373. // We consider we are on a webgl1 capable device
  81374. _this._caps = new BABYLON.EngineCapabilities();
  81375. _this._caps.maxTexturesImageUnits = 16;
  81376. _this._caps.maxVertexTextureImageUnits = 16;
  81377. _this._caps.maxTextureSize = 512;
  81378. _this._caps.maxCubemapTextureSize = 512;
  81379. _this._caps.maxRenderTextureSize = 512;
  81380. _this._caps.maxVertexAttribs = 16;
  81381. _this._caps.maxVaryingVectors = 16;
  81382. _this._caps.maxFragmentUniformVectors = 16;
  81383. _this._caps.maxVertexUniformVectors = 16;
  81384. // Extensions
  81385. _this._caps.standardDerivatives = false;
  81386. _this._caps.astc = null;
  81387. _this._caps.s3tc = null;
  81388. _this._caps.pvrtc = null;
  81389. _this._caps.etc1 = null;
  81390. _this._caps.etc2 = null;
  81391. _this._caps.textureAnisotropicFilterExtension = null;
  81392. _this._caps.maxAnisotropy = 0;
  81393. _this._caps.uintIndices = false;
  81394. _this._caps.fragmentDepthSupported = false;
  81395. _this._caps.highPrecisionShaderSupported = true;
  81396. _this._caps.colorBufferFloat = false;
  81397. _this._caps.textureFloat = false;
  81398. _this._caps.textureFloatLinearFiltering = false;
  81399. _this._caps.textureFloatRender = false;
  81400. _this._caps.textureHalfFloat = false;
  81401. _this._caps.textureHalfFloatLinearFiltering = false;
  81402. _this._caps.textureHalfFloatRender = false;
  81403. _this._caps.textureLOD = false;
  81404. _this._caps.drawBuffersExtension = false;
  81405. _this._caps.depthTextureExtension = false;
  81406. _this._caps.vertexArrayObject = false;
  81407. _this._caps.instancedArrays = false;
  81408. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  81409. // Wrappers
  81410. if (typeof URL === "undefined") {
  81411. URL = {
  81412. createObjectURL: function () { },
  81413. revokeObjectURL: function () { }
  81414. };
  81415. }
  81416. if (typeof Blob === "undefined") {
  81417. Blob = function () { };
  81418. }
  81419. return _this;
  81420. }
  81421. NullEngine.prototype.isDeterministicLockStep = function () {
  81422. return this._options.deterministicLockstep;
  81423. };
  81424. NullEngine.prototype.getLockstepMaxSteps = function () {
  81425. return this._options.lockstepMaxSteps;
  81426. };
  81427. NullEngine.prototype.createVertexBuffer = function (vertices) {
  81428. return {
  81429. capacity: 0,
  81430. references: 1,
  81431. is32Bits: false
  81432. };
  81433. };
  81434. NullEngine.prototype.createIndexBuffer = function (indices) {
  81435. return {
  81436. capacity: 0,
  81437. references: 1,
  81438. is32Bits: false
  81439. };
  81440. };
  81441. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  81442. if (stencil === void 0) { stencil = false; }
  81443. };
  81444. NullEngine.prototype.getRenderWidth = function (useScreen) {
  81445. if (useScreen === void 0) { useScreen = false; }
  81446. if (!useScreen && this._currentRenderTarget) {
  81447. return this._currentRenderTarget.width;
  81448. }
  81449. return this._options.renderWidth;
  81450. };
  81451. NullEngine.prototype.getRenderHeight = function (useScreen) {
  81452. if (useScreen === void 0) { useScreen = false; }
  81453. if (!useScreen && this._currentRenderTarget) {
  81454. return this._currentRenderTarget.height;
  81455. }
  81456. return this._options.renderHeight;
  81457. };
  81458. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  81459. this._cachedViewport = viewport;
  81460. };
  81461. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  81462. return {
  81463. transformFeedback: null,
  81464. __SPECTOR_rebuildProgram: null
  81465. };
  81466. };
  81467. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  81468. return [];
  81469. };
  81470. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  81471. return [];
  81472. };
  81473. NullEngine.prototype.bindSamplers = function (effect) {
  81474. this._currentEffect = null;
  81475. };
  81476. NullEngine.prototype.enableEffect = function (effect) {
  81477. this._currentEffect = effect;
  81478. if (effect.onBind) {
  81479. effect.onBind(effect);
  81480. }
  81481. effect.onBindObservable.notifyObservers(effect);
  81482. };
  81483. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  81484. if (zOffset === void 0) { zOffset = 0; }
  81485. if (reverseSide === void 0) { reverseSide = false; }
  81486. };
  81487. NullEngine.prototype.setIntArray = function (uniform, array) {
  81488. };
  81489. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  81490. };
  81491. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  81492. };
  81493. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  81494. };
  81495. NullEngine.prototype.setFloatArray = function (uniform, array) {
  81496. };
  81497. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  81498. };
  81499. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  81500. };
  81501. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  81502. };
  81503. NullEngine.prototype.setArray = function (uniform, array) {
  81504. };
  81505. NullEngine.prototype.setArray2 = function (uniform, array) {
  81506. };
  81507. NullEngine.prototype.setArray3 = function (uniform, array) {
  81508. };
  81509. NullEngine.prototype.setArray4 = function (uniform, array) {
  81510. };
  81511. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  81512. };
  81513. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  81514. };
  81515. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  81516. };
  81517. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  81518. };
  81519. NullEngine.prototype.setFloat = function (uniform, value) {
  81520. };
  81521. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  81522. };
  81523. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  81524. };
  81525. NullEngine.prototype.setBool = function (uniform, bool) {
  81526. };
  81527. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  81528. };
  81529. NullEngine.prototype.setColor3 = function (uniform, color3) {
  81530. };
  81531. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  81532. };
  81533. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  81534. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  81535. if (this._alphaMode === mode) {
  81536. return;
  81537. }
  81538. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  81539. if (!noDepthWriteChange) {
  81540. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  81541. }
  81542. this._alphaMode = mode;
  81543. };
  81544. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  81545. };
  81546. NullEngine.prototype.wipeCaches = function (bruteForce) {
  81547. if (this.preventCacheWipeBetweenFrames) {
  81548. return;
  81549. }
  81550. this.resetTextureCache();
  81551. this._currentEffect = null;
  81552. if (bruteForce) {
  81553. this._currentProgram = null;
  81554. this._stencilState.reset();
  81555. this._depthCullingState.reset();
  81556. this.setDepthFunctionToLessOrEqual();
  81557. this._alphaState.reset();
  81558. }
  81559. this._cachedVertexBuffers = null;
  81560. this._cachedIndexBuffer = null;
  81561. this._cachedEffectForVertexBuffers = null;
  81562. };
  81563. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  81564. };
  81565. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  81566. };
  81567. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  81568. };
  81569. NullEngine.prototype._createTexture = function () {
  81570. return {};
  81571. };
  81572. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  81573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81574. if (onLoad === void 0) { onLoad = null; }
  81575. if (onError === void 0) { onError = null; }
  81576. if (buffer === void 0) { buffer = null; }
  81577. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  81578. var url = String(urlArg);
  81579. texture.url = url;
  81580. texture.generateMipMaps = !noMipmap;
  81581. texture.samplingMode = samplingMode;
  81582. texture.invertY = invertY;
  81583. texture.baseWidth = this._options.textureSize;
  81584. texture.baseHeight = this._options.textureSize;
  81585. texture.width = this._options.textureSize;
  81586. texture.height = this._options.textureSize;
  81587. if (format) {
  81588. texture.format = format;
  81589. }
  81590. texture.isReady = true;
  81591. if (onLoad) {
  81592. onLoad();
  81593. }
  81594. return texture;
  81595. };
  81596. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  81597. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  81598. if (options !== undefined && typeof options === "object") {
  81599. fullOptions.generateMipMaps = options.generateMipMaps;
  81600. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  81601. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  81602. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  81603. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  81604. }
  81605. else {
  81606. fullOptions.generateMipMaps = options;
  81607. fullOptions.generateDepthBuffer = true;
  81608. fullOptions.generateStencilBuffer = false;
  81609. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81610. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81611. }
  81612. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  81613. var width = size.width || size;
  81614. var height = size.height || size;
  81615. texture._depthStencilBuffer = {};
  81616. texture._framebuffer = {};
  81617. texture.baseWidth = width;
  81618. texture.baseHeight = height;
  81619. texture.width = width;
  81620. texture.height = height;
  81621. texture.isReady = true;
  81622. texture.samples = 1;
  81623. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  81624. texture.samplingMode = fullOptions.samplingMode;
  81625. texture.type = fullOptions.type;
  81626. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  81627. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  81628. return texture;
  81629. };
  81630. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  81631. texture.samplingMode = samplingMode;
  81632. };
  81633. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  81634. if (this._currentRenderTarget) {
  81635. this.unBindFramebuffer(this._currentRenderTarget);
  81636. }
  81637. this._currentRenderTarget = texture;
  81638. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  81639. if (this._cachedViewport && !forceFullscreenViewport) {
  81640. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  81641. }
  81642. };
  81643. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  81644. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  81645. this._currentRenderTarget = null;
  81646. if (onBeforeUnbind) {
  81647. if (texture._MSAAFramebuffer) {
  81648. this._currentFramebuffer = texture._framebuffer;
  81649. }
  81650. onBeforeUnbind();
  81651. }
  81652. this._currentFramebuffer = null;
  81653. };
  81654. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  81655. var vbo = {
  81656. capacity: 1,
  81657. references: 1,
  81658. is32Bits: false
  81659. };
  81660. return vbo;
  81661. };
  81662. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  81663. if (offset === void 0) { offset = 0; }
  81664. };
  81665. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  81666. };
  81667. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  81668. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  81669. this._boundTexturesCache[this._activeChannel] = texture;
  81670. }
  81671. };
  81672. NullEngine.prototype._bindTexture = function (channel, texture) {
  81673. if (channel < 0) {
  81674. return;
  81675. }
  81676. this._bindTextureDirectly(0, texture);
  81677. };
  81678. NullEngine.prototype._releaseBuffer = function (buffer) {
  81679. buffer.references--;
  81680. if (buffer.references === 0) {
  81681. return true;
  81682. }
  81683. return false;
  81684. };
  81685. return NullEngine;
  81686. }(BABYLON.Engine));
  81687. BABYLON.NullEngine = NullEngine;
  81688. })(BABYLON || (BABYLON = {}));
  81689. //# sourceMappingURL=babylon.nullEngine.js.map
  81690. var BABYLON;
  81691. (function (BABYLON) {
  81692. /**
  81693. * This class can be used to get instrumentation data from a Babylon engine
  81694. */
  81695. var EngineInstrumentation = /** @class */ (function () {
  81696. function EngineInstrumentation(engine) {
  81697. this.engine = engine;
  81698. this._captureGPUFrameTime = false;
  81699. this._gpuFrameTime = new BABYLON.PerfCounter();
  81700. this._captureShaderCompilationTime = false;
  81701. this._shaderCompilationTime = new BABYLON.PerfCounter();
  81702. // Observers
  81703. this._onBeginFrameObserver = null;
  81704. this._onEndFrameObserver = null;
  81705. this._onBeforeShaderCompilationObserver = null;
  81706. this._onAfterShaderCompilationObserver = null;
  81707. }
  81708. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  81709. // Properties
  81710. /**
  81711. * Gets the perf counter used for GPU frame time
  81712. */
  81713. get: function () {
  81714. return this._gpuFrameTime;
  81715. },
  81716. enumerable: true,
  81717. configurable: true
  81718. });
  81719. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  81720. /**
  81721. * Gets the GPU frame time capture status
  81722. */
  81723. get: function () {
  81724. return this._captureGPUFrameTime;
  81725. },
  81726. /**
  81727. * Enable or disable the GPU frame time capture
  81728. */
  81729. set: function (value) {
  81730. var _this = this;
  81731. if (value === this._captureGPUFrameTime) {
  81732. return;
  81733. }
  81734. this._captureGPUFrameTime = value;
  81735. if (value) {
  81736. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  81737. if (!_this._gpuFrameTimeToken) {
  81738. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  81739. }
  81740. });
  81741. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  81742. if (!_this._gpuFrameTimeToken) {
  81743. return;
  81744. }
  81745. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  81746. if (time > -1) {
  81747. _this._gpuFrameTimeToken = null;
  81748. _this._gpuFrameTime.fetchNewFrame();
  81749. _this._gpuFrameTime.addCount(time, true);
  81750. }
  81751. });
  81752. }
  81753. else {
  81754. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81755. this._onBeginFrameObserver = null;
  81756. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81757. this._onEndFrameObserver = null;
  81758. }
  81759. },
  81760. enumerable: true,
  81761. configurable: true
  81762. });
  81763. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  81764. /**
  81765. * Gets the perf counter used for shader compilation time
  81766. */
  81767. get: function () {
  81768. return this._shaderCompilationTime;
  81769. },
  81770. enumerable: true,
  81771. configurable: true
  81772. });
  81773. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  81774. /**
  81775. * Gets the shader compilation time capture status
  81776. */
  81777. get: function () {
  81778. return this._captureShaderCompilationTime;
  81779. },
  81780. /**
  81781. * Enable or disable the shader compilation time capture
  81782. */
  81783. set: function (value) {
  81784. var _this = this;
  81785. if (value === this._captureShaderCompilationTime) {
  81786. return;
  81787. }
  81788. this._captureShaderCompilationTime = value;
  81789. if (value) {
  81790. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  81791. _this._shaderCompilationTime.fetchNewFrame();
  81792. _this._shaderCompilationTime.beginMonitoring();
  81793. });
  81794. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  81795. _this._shaderCompilationTime.endMonitoring();
  81796. });
  81797. }
  81798. else {
  81799. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81800. this._onBeforeShaderCompilationObserver = null;
  81801. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81802. this._onAfterShaderCompilationObserver = null;
  81803. }
  81804. },
  81805. enumerable: true,
  81806. configurable: true
  81807. });
  81808. EngineInstrumentation.prototype.dispose = function () {
  81809. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81810. this._onBeginFrameObserver = null;
  81811. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81812. this._onEndFrameObserver = null;
  81813. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81814. this._onBeforeShaderCompilationObserver = null;
  81815. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81816. this._onAfterShaderCompilationObserver = null;
  81817. this.engine = null;
  81818. };
  81819. return EngineInstrumentation;
  81820. }());
  81821. BABYLON.EngineInstrumentation = EngineInstrumentation;
  81822. })(BABYLON || (BABYLON = {}));
  81823. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  81824. var BABYLON;
  81825. (function (BABYLON) {
  81826. /**
  81827. * This class can be used to get instrumentation data from a Babylon engine
  81828. */
  81829. var SceneInstrumentation = /** @class */ (function () {
  81830. function SceneInstrumentation(scene) {
  81831. var _this = this;
  81832. this.scene = scene;
  81833. this._captureActiveMeshesEvaluationTime = false;
  81834. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  81835. this._captureRenderTargetsRenderTime = false;
  81836. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  81837. this._captureFrameTime = false;
  81838. this._frameTime = new BABYLON.PerfCounter();
  81839. this._captureRenderTime = false;
  81840. this._renderTime = new BABYLON.PerfCounter();
  81841. this._captureInterFrameTime = false;
  81842. this._interFrameTime = new BABYLON.PerfCounter();
  81843. this._captureParticlesRenderTime = false;
  81844. this._particlesRenderTime = new BABYLON.PerfCounter();
  81845. this._captureSpritesRenderTime = false;
  81846. this._spritesRenderTime = new BABYLON.PerfCounter();
  81847. this._capturePhysicsTime = false;
  81848. this._physicsTime = new BABYLON.PerfCounter();
  81849. this._captureAnimationsTime = false;
  81850. this._animationsTime = new BABYLON.PerfCounter();
  81851. // Observers
  81852. this._onBeforeActiveMeshesEvaluationObserver = null;
  81853. this._onAfterActiveMeshesEvaluationObserver = null;
  81854. this._onBeforeRenderTargetsRenderObserver = null;
  81855. this._onAfterRenderTargetsRenderObserver = null;
  81856. this._onAfterRenderObserver = null;
  81857. this._onBeforeDrawPhaseObserver = null;
  81858. this._onAfterDrawPhaseObserver = null;
  81859. this._onBeforeAnimationsObserver = null;
  81860. this._onBeforeParticlesRenderingObserver = null;
  81861. this._onAfterParticlesRenderingObserver = null;
  81862. this._onBeforeSpritesRenderingObserver = null;
  81863. this._onAfterSpritesRenderingObserver = null;
  81864. this._onBeforePhysicsObserver = null;
  81865. this._onAfterPhysicsObserver = null;
  81866. this._onAfterAnimationsObserver = null;
  81867. // Before render
  81868. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  81869. if (_this._captureActiveMeshesEvaluationTime) {
  81870. _this._activeMeshesEvaluationTime.fetchNewFrame();
  81871. }
  81872. if (_this._captureRenderTargetsRenderTime) {
  81873. _this._renderTargetsRenderTime.fetchNewFrame();
  81874. }
  81875. if (_this._captureFrameTime) {
  81876. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  81877. _this._frameTime.beginMonitoring();
  81878. }
  81879. if (_this._captureInterFrameTime) {
  81880. _this._interFrameTime.endMonitoring();
  81881. }
  81882. if (_this._captureParticlesRenderTime) {
  81883. _this._particlesRenderTime.fetchNewFrame();
  81884. }
  81885. if (_this._captureSpritesRenderTime) {
  81886. _this._spritesRenderTime.fetchNewFrame();
  81887. }
  81888. if (_this._captureAnimationsTime) {
  81889. _this._animationsTime.beginMonitoring();
  81890. }
  81891. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  81892. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  81893. });
  81894. // After render
  81895. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  81896. if (_this._captureFrameTime) {
  81897. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  81898. _this._frameTime.endMonitoring();
  81899. }
  81900. if (_this._captureRenderTime) {
  81901. _this._renderTime.endMonitoring(false);
  81902. }
  81903. if (_this._captureInterFrameTime) {
  81904. _this._interFrameTime.beginMonitoring();
  81905. }
  81906. });
  81907. }
  81908. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  81909. // Properties
  81910. /**
  81911. * Gets the perf counter used for active meshes evaluation time
  81912. */
  81913. get: function () {
  81914. return this._activeMeshesEvaluationTime;
  81915. },
  81916. enumerable: true,
  81917. configurable: true
  81918. });
  81919. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  81920. /**
  81921. * Gets the active meshes evaluation time capture status
  81922. */
  81923. get: function () {
  81924. return this._captureActiveMeshesEvaluationTime;
  81925. },
  81926. /**
  81927. * Enable or disable the active meshes evaluation time capture
  81928. */
  81929. set: function (value) {
  81930. var _this = this;
  81931. if (value === this._captureActiveMeshesEvaluationTime) {
  81932. return;
  81933. }
  81934. this._captureActiveMeshesEvaluationTime = value;
  81935. if (value) {
  81936. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  81937. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  81938. _this._activeMeshesEvaluationTime.beginMonitoring();
  81939. });
  81940. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  81941. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  81942. _this._activeMeshesEvaluationTime.endMonitoring();
  81943. });
  81944. }
  81945. else {
  81946. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  81947. this._onBeforeActiveMeshesEvaluationObserver = null;
  81948. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  81949. this._onAfterActiveMeshesEvaluationObserver = null;
  81950. }
  81951. },
  81952. enumerable: true,
  81953. configurable: true
  81954. });
  81955. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  81956. /**
  81957. * Gets the perf counter used for render targets render time
  81958. */
  81959. get: function () {
  81960. return this._renderTargetsRenderTime;
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  81966. /**
  81967. * Gets the render targets render time capture status
  81968. */
  81969. get: function () {
  81970. return this._captureRenderTargetsRenderTime;
  81971. },
  81972. /**
  81973. * Enable or disable the render targets render time capture
  81974. */
  81975. set: function (value) {
  81976. var _this = this;
  81977. if (value === this._captureRenderTargetsRenderTime) {
  81978. return;
  81979. }
  81980. this._captureRenderTargetsRenderTime = value;
  81981. if (value) {
  81982. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  81983. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  81984. _this._renderTargetsRenderTime.beginMonitoring();
  81985. });
  81986. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  81987. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  81988. _this._renderTargetsRenderTime.endMonitoring(false);
  81989. });
  81990. }
  81991. else {
  81992. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  81993. this._onBeforeRenderTargetsRenderObserver = null;
  81994. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  81995. this._onAfterRenderTargetsRenderObserver = null;
  81996. }
  81997. },
  81998. enumerable: true,
  81999. configurable: true
  82000. });
  82001. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82002. /**
  82003. * Gets the perf counter used for particles render time
  82004. */
  82005. get: function () {
  82006. return this._particlesRenderTime;
  82007. },
  82008. enumerable: true,
  82009. configurable: true
  82010. });
  82011. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82012. /**
  82013. * Gets the particles render time capture status
  82014. */
  82015. get: function () {
  82016. return this._captureParticlesRenderTime;
  82017. },
  82018. /**
  82019. * Enable or disable the particles render time capture
  82020. */
  82021. set: function (value) {
  82022. var _this = this;
  82023. if (value === this._captureParticlesRenderTime) {
  82024. return;
  82025. }
  82026. this._captureParticlesRenderTime = value;
  82027. if (value) {
  82028. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82029. BABYLON.Tools.StartPerformanceCounter("Particles");
  82030. _this._particlesRenderTime.beginMonitoring();
  82031. });
  82032. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82033. BABYLON.Tools.EndPerformanceCounter("Particles");
  82034. _this._particlesRenderTime.endMonitoring(false);
  82035. });
  82036. }
  82037. else {
  82038. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82039. this._onBeforeParticlesRenderingObserver = null;
  82040. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82041. this._onAfterParticlesRenderingObserver = null;
  82042. }
  82043. },
  82044. enumerable: true,
  82045. configurable: true
  82046. });
  82047. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82048. /**
  82049. * Gets the perf counter used for sprites render time
  82050. */
  82051. get: function () {
  82052. return this._spritesRenderTime;
  82053. },
  82054. enumerable: true,
  82055. configurable: true
  82056. });
  82057. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82058. /**
  82059. * Gets the sprites render time capture status
  82060. */
  82061. get: function () {
  82062. return this._captureSpritesRenderTime;
  82063. },
  82064. /**
  82065. * Enable or disable the sprites render time capture
  82066. */
  82067. set: function (value) {
  82068. var _this = this;
  82069. if (value === this._captureSpritesRenderTime) {
  82070. return;
  82071. }
  82072. this._captureSpritesRenderTime = value;
  82073. if (value) {
  82074. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82075. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82076. _this._spritesRenderTime.beginMonitoring();
  82077. });
  82078. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82079. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82080. _this._spritesRenderTime.endMonitoring(false);
  82081. });
  82082. }
  82083. else {
  82084. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82085. this._onBeforeSpritesRenderingObserver = null;
  82086. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82087. this._onAfterSpritesRenderingObserver = null;
  82088. }
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82094. /**
  82095. * Gets the perf counter used for physics time
  82096. */
  82097. get: function () {
  82098. return this._physicsTime;
  82099. },
  82100. enumerable: true,
  82101. configurable: true
  82102. });
  82103. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82104. /**
  82105. * Gets the physics time capture status
  82106. */
  82107. get: function () {
  82108. return this._capturePhysicsTime;
  82109. },
  82110. /**
  82111. * Enable or disable the physics time capture
  82112. */
  82113. set: function (value) {
  82114. var _this = this;
  82115. if (value === this._capturePhysicsTime) {
  82116. return;
  82117. }
  82118. this._capturePhysicsTime = value;
  82119. if (value) {
  82120. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82121. BABYLON.Tools.StartPerformanceCounter("Physics");
  82122. _this._physicsTime.beginMonitoring();
  82123. });
  82124. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82125. BABYLON.Tools.EndPerformanceCounter("Physics");
  82126. _this._physicsTime.endMonitoring();
  82127. });
  82128. }
  82129. else {
  82130. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82131. this._onBeforePhysicsObserver = null;
  82132. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82133. this._onAfterPhysicsObserver = null;
  82134. }
  82135. },
  82136. enumerable: true,
  82137. configurable: true
  82138. });
  82139. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82140. /**
  82141. * Gets the perf counter used for animations time
  82142. */
  82143. get: function () {
  82144. return this._animationsTime;
  82145. },
  82146. enumerable: true,
  82147. configurable: true
  82148. });
  82149. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82150. /**
  82151. * Gets the animations time capture status
  82152. */
  82153. get: function () {
  82154. return this._captureAnimationsTime;
  82155. },
  82156. /**
  82157. * Enable or disable the animations time capture
  82158. */
  82159. set: function (value) {
  82160. var _this = this;
  82161. if (value === this._captureAnimationsTime) {
  82162. return;
  82163. }
  82164. this._captureAnimationsTime = value;
  82165. if (value) {
  82166. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82167. _this._animationsTime.endMonitoring();
  82168. });
  82169. }
  82170. else {
  82171. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82172. this._onAfterAnimationsObserver = null;
  82173. }
  82174. },
  82175. enumerable: true,
  82176. configurable: true
  82177. });
  82178. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82179. /**
  82180. * Gets the perf counter used for frame time capture
  82181. */
  82182. get: function () {
  82183. return this._frameTime;
  82184. },
  82185. enumerable: true,
  82186. configurable: true
  82187. });
  82188. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82189. /**
  82190. * Gets the frame time capture status
  82191. */
  82192. get: function () {
  82193. return this._captureFrameTime;
  82194. },
  82195. /**
  82196. * Enable or disable the frame time capture
  82197. */
  82198. set: function (value) {
  82199. this._captureFrameTime = value;
  82200. },
  82201. enumerable: true,
  82202. configurable: true
  82203. });
  82204. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82205. /**
  82206. * Gets the perf counter used for inter-frames time capture
  82207. */
  82208. get: function () {
  82209. return this._interFrameTime;
  82210. },
  82211. enumerable: true,
  82212. configurable: true
  82213. });
  82214. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82215. /**
  82216. * Gets the inter-frames time capture status
  82217. */
  82218. get: function () {
  82219. return this._captureInterFrameTime;
  82220. },
  82221. /**
  82222. * Enable or disable the inter-frames time capture
  82223. */
  82224. set: function (value) {
  82225. this._captureInterFrameTime = value;
  82226. },
  82227. enumerable: true,
  82228. configurable: true
  82229. });
  82230. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82231. /**
  82232. * Gets the perf counter used for render time capture
  82233. */
  82234. get: function () {
  82235. return this._renderTime;
  82236. },
  82237. enumerable: true,
  82238. configurable: true
  82239. });
  82240. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82241. /**
  82242. * Gets the render time capture status
  82243. */
  82244. get: function () {
  82245. return this._captureRenderTime;
  82246. },
  82247. /**
  82248. * Enable or disable the render time capture
  82249. */
  82250. set: function (value) {
  82251. var _this = this;
  82252. if (value === this._captureRenderTime) {
  82253. return;
  82254. }
  82255. this._captureRenderTime = value;
  82256. if (value) {
  82257. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82258. _this._renderTime.beginMonitoring();
  82259. BABYLON.Tools.StartPerformanceCounter("Main render");
  82260. });
  82261. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82262. _this._renderTime.endMonitoring(false);
  82263. BABYLON.Tools.EndPerformanceCounter("Main render");
  82264. });
  82265. }
  82266. else {
  82267. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82268. this._onBeforeDrawPhaseObserver = null;
  82269. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82270. this._onAfterDrawPhaseObserver = null;
  82271. }
  82272. },
  82273. enumerable: true,
  82274. configurable: true
  82275. });
  82276. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82277. /**
  82278. * Gets the perf counter used for draw calls
  82279. */
  82280. get: function () {
  82281. return this.scene.getEngine()._drawCalls;
  82282. },
  82283. enumerable: true,
  82284. configurable: true
  82285. });
  82286. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82287. /**
  82288. * Gets the perf counter used for texture collisions
  82289. */
  82290. get: function () {
  82291. return this.scene.getEngine()._textureCollisions;
  82292. },
  82293. enumerable: true,
  82294. configurable: true
  82295. });
  82296. SceneInstrumentation.prototype.dispose = function () {
  82297. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82298. this._onAfterRenderObserver = null;
  82299. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82300. this._onBeforeActiveMeshesEvaluationObserver = null;
  82301. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82302. this._onAfterActiveMeshesEvaluationObserver = null;
  82303. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82304. this._onBeforeRenderTargetsRenderObserver = null;
  82305. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82306. this._onAfterRenderTargetsRenderObserver = null;
  82307. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  82308. this._onBeforeAnimationsObserver = null;
  82309. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82310. this._onBeforeParticlesRenderingObserver = null;
  82311. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82312. this._onAfterParticlesRenderingObserver = null;
  82313. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82314. this._onBeforeSpritesRenderingObserver = null;
  82315. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82316. this._onAfterSpritesRenderingObserver = null;
  82317. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82318. this._onBeforeDrawPhaseObserver = null;
  82319. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82320. this._onAfterDrawPhaseObserver = null;
  82321. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82322. this._onBeforePhysicsObserver = null;
  82323. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82324. this._onAfterPhysicsObserver = null;
  82325. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82326. this._onAfterAnimationsObserver = null;
  82327. this.scene = null;
  82328. };
  82329. return SceneInstrumentation;
  82330. }());
  82331. BABYLON.SceneInstrumentation = SceneInstrumentation;
  82332. })(BABYLON || (BABYLON = {}));
  82333. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  82334. var BABYLON;
  82335. (function (BABYLON) {
  82336. var _TimeToken = /** @class */ (function () {
  82337. function _TimeToken() {
  82338. this._timeElapsedQueryEnded = false;
  82339. }
  82340. return _TimeToken;
  82341. }());
  82342. BABYLON._TimeToken = _TimeToken;
  82343. })(BABYLON || (BABYLON = {}));
  82344. //# sourceMappingURL=babylon.timeToken.js.map
  82345. var BABYLON;
  82346. (function (BABYLON) {
  82347. /**
  82348. * Background material defines definition.
  82349. */
  82350. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  82351. __extends(BackgroundMaterialDefines, _super);
  82352. /**
  82353. * Constructor of the defines.
  82354. */
  82355. function BackgroundMaterialDefines() {
  82356. var _this = _super.call(this) || this;
  82357. /**
  82358. * True if the diffuse texture is in use.
  82359. */
  82360. _this.DIFFUSE = false;
  82361. /**
  82362. * The direct UV channel to use.
  82363. */
  82364. _this.DIFFUSEDIRECTUV = 0;
  82365. /**
  82366. * True if the diffuse texture is in gamma space.
  82367. */
  82368. _this.GAMMADIFFUSE = false;
  82369. /**
  82370. * True if the diffuse texture has opacity in the alpha channel.
  82371. */
  82372. _this.DIFFUSEHASALPHA = false;
  82373. /**
  82374. * True if you want the material to fade to transparent at grazing angle.
  82375. */
  82376. _this.OPACITYFRESNEL = false;
  82377. /**
  82378. * True if an extra blur needs to be added in the reflection.
  82379. */
  82380. _this.REFLECTIONBLUR = false;
  82381. /**
  82382. * True if you want the material to fade to reflection at grazing angle.
  82383. */
  82384. _this.REFLECTIONFRESNEL = false;
  82385. /**
  82386. * True if you want the material to falloff as far as you move away from the scene center.
  82387. */
  82388. _this.REFLECTIONFALLOFF = false;
  82389. /**
  82390. * False if the current Webgl implementation does not support the texture lod extension.
  82391. */
  82392. _this.TEXTURELODSUPPORT = false;
  82393. /**
  82394. * True to ensure the data are premultiplied.
  82395. */
  82396. _this.PREMULTIPLYALPHA = false;
  82397. /**
  82398. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  82399. */
  82400. _this.USERGBCOLOR = false;
  82401. /**
  82402. * True to add noise in order to reduce the banding effect.
  82403. */
  82404. _this.NOISE = false;
  82405. // Image Processing Configuration.
  82406. _this.IMAGEPROCESSING = false;
  82407. _this.VIGNETTE = false;
  82408. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82409. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82410. _this.TONEMAPPING = false;
  82411. _this.CONTRAST = false;
  82412. _this.COLORCURVES = false;
  82413. _this.COLORGRADING = false;
  82414. _this.COLORGRADING3D = false;
  82415. _this.SAMPLER3DGREENDEPTH = false;
  82416. _this.SAMPLER3DBGRMAP = false;
  82417. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82418. _this.EXPOSURE = false;
  82419. // Reflection.
  82420. _this.REFLECTION = false;
  82421. _this.REFLECTIONMAP_3D = false;
  82422. _this.REFLECTIONMAP_SPHERICAL = false;
  82423. _this.REFLECTIONMAP_PLANAR = false;
  82424. _this.REFLECTIONMAP_CUBIC = false;
  82425. _this.REFLECTIONMAP_PROJECTION = false;
  82426. _this.REFLECTIONMAP_SKYBOX = false;
  82427. _this.REFLECTIONMAP_EXPLICIT = false;
  82428. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82429. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82430. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82431. _this.INVERTCUBICMAP = false;
  82432. _this.REFLECTIONMAP_OPPOSITEZ = false;
  82433. _this.LODINREFLECTIONALPHA = false;
  82434. _this.GAMMAREFLECTION = false;
  82435. // Default BJS.
  82436. _this.MAINUV1 = false;
  82437. _this.MAINUV2 = false;
  82438. _this.UV1 = false;
  82439. _this.UV2 = false;
  82440. _this.CLIPPLANE = false;
  82441. _this.POINTSIZE = false;
  82442. _this.FOG = false;
  82443. _this.NORMAL = false;
  82444. _this.NUM_BONE_INFLUENCERS = 0;
  82445. _this.BonesPerMesh = 0;
  82446. _this.INSTANCES = false;
  82447. _this.SHADOWFLOAT = false;
  82448. _this.rebuild();
  82449. return _this;
  82450. }
  82451. return BackgroundMaterialDefines;
  82452. }(BABYLON.MaterialDefines));
  82453. /**
  82454. * Background material used to create an efficient environement around your scene.
  82455. */
  82456. var BackgroundMaterial = /** @class */ (function (_super) {
  82457. __extends(BackgroundMaterial, _super);
  82458. /**
  82459. * constructor
  82460. * @param name The name of the material
  82461. * @param scene The scene to add the material to
  82462. */
  82463. function BackgroundMaterial(name, scene) {
  82464. var _this = _super.call(this, name, scene) || this;
  82465. _this.primaryColor = BABYLON.Color3.White();
  82466. _this.primaryLevel = 1;
  82467. _this.secondaryColor = BABYLON.Color3.Gray();
  82468. _this.secondaryLevel = 1;
  82469. _this.tertiaryColor = BABYLON.Color3.Black();
  82470. _this.tertiaryLevel = 1;
  82471. _this.reflectionTexture = null;
  82472. _this.reflectionBlur = 0;
  82473. _this.diffuseTexture = null;
  82474. /**
  82475. * Specify the list of lights casting shadow on the material.
  82476. * All scene shadow lights will be included if null.
  82477. */
  82478. _this._shadowLights = null;
  82479. _this.shadowLights = null;
  82480. _this.shadowBlurScale = 1;
  82481. _this.shadowLevel = 0;
  82482. _this.sceneCenter = BABYLON.Vector3.Zero();
  82483. _this.opacityFresnel = true;
  82484. _this.reflectionFresnel = false;
  82485. _this.reflectionFalloffDistance = 0.0;
  82486. _this.reflectionAmount = 1.0;
  82487. _this.reflectionReflectance0 = 0.05;
  82488. _this.reflectionReflectance90 = 0.5;
  82489. _this.useRGBColor = true;
  82490. _this.enableNoise = false;
  82491. /**
  82492. * Number of Simultaneous lights allowed on the material.
  82493. */
  82494. _this._maxSimultaneousLights = 4;
  82495. _this.maxSimultaneousLights = 4;
  82496. /**
  82497. * Keep track of the image processing observer to allow dispose and replace.
  82498. */
  82499. _this._imageProcessingObserver = null;
  82500. // Temp values kept as cache in the material.
  82501. _this._renderTargets = new BABYLON.SmartArray(16);
  82502. _this._reflectionControls = BABYLON.Vector4.Zero();
  82503. // Setup the default processing configuration to the scene.
  82504. _this._attachImageProcessingConfiguration(null);
  82505. _this.getRenderTargetTextures = function () {
  82506. _this._renderTargets.reset();
  82507. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  82508. _this._renderTargets.push(_this._diffuseTexture);
  82509. }
  82510. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  82511. _this._renderTargets.push(_this._reflectionTexture);
  82512. }
  82513. return _this._renderTargets;
  82514. };
  82515. return _this;
  82516. }
  82517. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  82518. /**
  82519. * Sets the reflection reflectance fresnel values according to the default standard
  82520. * empirically know to work well :-)
  82521. */
  82522. set: function (value) {
  82523. var reflectionWeight = value;
  82524. if (reflectionWeight < 0.5) {
  82525. reflectionWeight = reflectionWeight * 2.0;
  82526. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  82527. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  82528. }
  82529. else {
  82530. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  82531. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  82532. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  82533. }
  82534. },
  82535. enumerable: true,
  82536. configurable: true
  82537. });
  82538. /**
  82539. * Attaches a new image processing configuration to the PBR Material.
  82540. * @param configuration (if null the scene configuration will be use)
  82541. */
  82542. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  82543. var _this = this;
  82544. if (configuration === this._imageProcessingConfiguration) {
  82545. return;
  82546. }
  82547. // Detaches observer.
  82548. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82549. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82550. }
  82551. // Pick the scene configuration if needed.
  82552. if (!configuration) {
  82553. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  82554. }
  82555. else {
  82556. this._imageProcessingConfiguration = configuration;
  82557. }
  82558. // Attaches observer.
  82559. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82560. _this._markAllSubMeshesAsImageProcessingDirty();
  82561. });
  82562. };
  82563. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  82564. /**
  82565. * Gets the image processing configuration used either in this material.
  82566. */
  82567. get: function () {
  82568. return this._imageProcessingConfiguration;
  82569. },
  82570. /**
  82571. * Sets the Default image processing configuration used either in the this material.
  82572. *
  82573. * If sets to null, the scene one is in use.
  82574. */
  82575. set: function (value) {
  82576. this._attachImageProcessingConfiguration(value);
  82577. // Ensure the effect will be rebuilt.
  82578. this._markAllSubMeshesAsTexturesDirty();
  82579. },
  82580. enumerable: true,
  82581. configurable: true
  82582. });
  82583. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  82584. /**
  82585. * Gets wether the color curves effect is enabled.
  82586. */
  82587. get: function () {
  82588. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82589. },
  82590. /**
  82591. * Sets wether the color curves effect is enabled.
  82592. */
  82593. set: function (value) {
  82594. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82595. },
  82596. enumerable: true,
  82597. configurable: true
  82598. });
  82599. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  82600. /**
  82601. * Gets wether the color grading effect is enabled.
  82602. */
  82603. get: function () {
  82604. return this.imageProcessingConfiguration.colorGradingEnabled;
  82605. },
  82606. /**
  82607. * Gets wether the color grading effect is enabled.
  82608. */
  82609. set: function (value) {
  82610. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82611. },
  82612. enumerable: true,
  82613. configurable: true
  82614. });
  82615. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  82616. /**
  82617. * Gets wether tonemapping is enabled or not.
  82618. */
  82619. get: function () {
  82620. return this._imageProcessingConfiguration.toneMappingEnabled;
  82621. },
  82622. /**
  82623. * Sets wether tonemapping is enabled or not
  82624. */
  82625. set: function (value) {
  82626. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82627. },
  82628. enumerable: true,
  82629. configurable: true
  82630. });
  82631. ;
  82632. ;
  82633. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  82634. /**
  82635. * The camera exposure used on this material.
  82636. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82637. * This corresponds to a photographic exposure.
  82638. */
  82639. get: function () {
  82640. return this._imageProcessingConfiguration.exposure;
  82641. },
  82642. /**
  82643. * The camera exposure used on this material.
  82644. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82645. * This corresponds to a photographic exposure.
  82646. */
  82647. set: function (value) {
  82648. this._imageProcessingConfiguration.exposure = value;
  82649. },
  82650. enumerable: true,
  82651. configurable: true
  82652. });
  82653. ;
  82654. ;
  82655. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  82656. /**
  82657. * Gets The camera contrast used on this material.
  82658. */
  82659. get: function () {
  82660. return this._imageProcessingConfiguration.contrast;
  82661. },
  82662. /**
  82663. * Sets The camera contrast used on this material.
  82664. */
  82665. set: function (value) {
  82666. this._imageProcessingConfiguration.contrast = value;
  82667. },
  82668. enumerable: true,
  82669. configurable: true
  82670. });
  82671. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  82672. /**
  82673. * Gets the Color Grading 2D Lookup Texture.
  82674. */
  82675. get: function () {
  82676. return this._imageProcessingConfiguration.colorGradingTexture;
  82677. },
  82678. /**
  82679. * Sets the Color Grading 2D Lookup Texture.
  82680. */
  82681. set: function (value) {
  82682. this.imageProcessingConfiguration.colorGradingTexture = value;
  82683. },
  82684. enumerable: true,
  82685. configurable: true
  82686. });
  82687. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  82688. /**
  82689. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82690. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82691. * 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;
  82692. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82693. */
  82694. get: function () {
  82695. return this.imageProcessingConfiguration.colorCurves;
  82696. },
  82697. /**
  82698. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82699. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82700. * 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;
  82701. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82702. */
  82703. set: function (value) {
  82704. this.imageProcessingConfiguration.colorCurves = value;
  82705. },
  82706. enumerable: true,
  82707. configurable: true
  82708. });
  82709. /**
  82710. * The entire material has been created in order to prevent overdraw.
  82711. * @returns false
  82712. */
  82713. BackgroundMaterial.prototype.needAlphaTesting = function () {
  82714. return true;
  82715. };
  82716. /**
  82717. * The entire material has been created in order to prevent overdraw.
  82718. * @returns true if blending is enable
  82719. */
  82720. BackgroundMaterial.prototype.needAlphaBlending = function () {
  82721. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  82722. };
  82723. /**
  82724. * Checks wether the material is ready to be rendered for a given mesh.
  82725. * @param mesh The mesh to render
  82726. * @param subMesh The submesh to check against
  82727. * @param useInstances Specify wether or not the material is used with instances
  82728. */
  82729. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  82730. var _this = this;
  82731. if (useInstances === void 0) { useInstances = false; }
  82732. if (subMesh.effect && this.isFrozen) {
  82733. if (this._wasPreviouslyReady) {
  82734. return true;
  82735. }
  82736. }
  82737. if (!subMesh._materialDefines) {
  82738. subMesh._materialDefines = new BackgroundMaterialDefines();
  82739. }
  82740. var scene = this.getScene();
  82741. var defines = subMesh._materialDefines;
  82742. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  82743. if (defines._renderId === scene.getRenderId()) {
  82744. return true;
  82745. }
  82746. }
  82747. var engine = scene.getEngine();
  82748. // Lights
  82749. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  82750. defines._needNormals = true;
  82751. // Textures
  82752. if (defines._areTexturesDirty) {
  82753. defines._needUVs = false;
  82754. if (scene.texturesEnabled) {
  82755. if (scene.getEngine().getCaps().textureLOD) {
  82756. defines.TEXTURELODSUPPORT = true;
  82757. }
  82758. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82759. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  82760. return false;
  82761. }
  82762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  82763. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  82764. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  82765. defines.OPACITYFRESNEL = this._opacityFresnel;
  82766. }
  82767. else {
  82768. defines.DIFFUSE = false;
  82769. defines.DIFFUSEHASALPHA = false;
  82770. defines.GAMMADIFFUSE = false;
  82771. defines.OPACITYFRESNEL = false;
  82772. }
  82773. var reflectionTexture = this._reflectionTexture;
  82774. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82775. if (!reflectionTexture.isReadyOrNotBlocking()) {
  82776. return false;
  82777. }
  82778. defines.REFLECTION = true;
  82779. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  82780. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  82781. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  82782. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  82783. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  82784. defines.INVERTCUBICMAP = true;
  82785. }
  82786. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  82787. switch (reflectionTexture.coordinatesMode) {
  82788. case BABYLON.Texture.CUBIC_MODE:
  82789. case BABYLON.Texture.INVCUBIC_MODE:
  82790. defines.REFLECTIONMAP_CUBIC = true;
  82791. break;
  82792. case BABYLON.Texture.EXPLICIT_MODE:
  82793. defines.REFLECTIONMAP_EXPLICIT = true;
  82794. break;
  82795. case BABYLON.Texture.PLANAR_MODE:
  82796. defines.REFLECTIONMAP_PLANAR = true;
  82797. break;
  82798. case BABYLON.Texture.PROJECTION_MODE:
  82799. defines.REFLECTIONMAP_PROJECTION = true;
  82800. break;
  82801. case BABYLON.Texture.SKYBOX_MODE:
  82802. defines.REFLECTIONMAP_SKYBOX = true;
  82803. break;
  82804. case BABYLON.Texture.SPHERICAL_MODE:
  82805. defines.REFLECTIONMAP_SPHERICAL = true;
  82806. break;
  82807. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  82808. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  82809. break;
  82810. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  82811. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  82812. break;
  82813. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  82814. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  82815. break;
  82816. }
  82817. if (this.reflectionFresnel) {
  82818. defines.REFLECTIONFRESNEL = true;
  82819. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  82820. this._reflectionControls.x = this.reflectionAmount;
  82821. this._reflectionControls.y = this.reflectionReflectance0;
  82822. this._reflectionControls.z = this.reflectionReflectance90;
  82823. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  82824. }
  82825. else {
  82826. defines.REFLECTIONFRESNEL = false;
  82827. defines.REFLECTIONFALLOFF = false;
  82828. }
  82829. }
  82830. else {
  82831. defines.REFLECTION = false;
  82832. defines.REFLECTIONFALLOFF = false;
  82833. defines.REFLECTIONBLUR = false;
  82834. defines.REFLECTIONMAP_3D = false;
  82835. defines.REFLECTIONMAP_SPHERICAL = false;
  82836. defines.REFLECTIONMAP_PLANAR = false;
  82837. defines.REFLECTIONMAP_CUBIC = false;
  82838. defines.REFLECTIONMAP_PROJECTION = false;
  82839. defines.REFLECTIONMAP_SKYBOX = false;
  82840. defines.REFLECTIONMAP_EXPLICIT = false;
  82841. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82842. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82843. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82844. defines.INVERTCUBICMAP = false;
  82845. defines.REFLECTIONMAP_OPPOSITEZ = false;
  82846. defines.LODINREFLECTIONALPHA = false;
  82847. defines.GAMMAREFLECTION = false;
  82848. }
  82849. }
  82850. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  82851. defines.USERGBCOLOR = this._useRGBColor;
  82852. defines.NOISE = this._enableNoise;
  82853. }
  82854. if (defines._areImageProcessingDirty) {
  82855. if (!this._imageProcessingConfiguration.isReady()) {
  82856. return false;
  82857. }
  82858. this._imageProcessingConfiguration.prepareDefines(defines);
  82859. }
  82860. // Misc.
  82861. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  82862. // Values that need to be evaluated on every frame
  82863. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  82864. // Attribs
  82865. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  82866. if (mesh) {
  82867. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  82868. mesh.createNormals(true);
  82869. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  82870. }
  82871. }
  82872. }
  82873. // Get correct effect
  82874. if (defines.isDirty) {
  82875. defines.markAsProcessed();
  82876. scene.resetCachedMaterial();
  82877. // Fallbacks
  82878. var fallbacks = new BABYLON.EffectFallbacks();
  82879. if (defines.FOG) {
  82880. fallbacks.addFallback(0, "FOG");
  82881. }
  82882. if (defines.POINTSIZE) {
  82883. fallbacks.addFallback(1, "POINTSIZE");
  82884. }
  82885. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  82886. if (defines.NUM_BONE_INFLUENCERS > 0) {
  82887. fallbacks.addCPUSkinningFallback(0, mesh);
  82888. }
  82889. //Attributes
  82890. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82891. if (defines.NORMAL) {
  82892. attribs.push(BABYLON.VertexBuffer.NormalKind);
  82893. }
  82894. if (defines.UV1) {
  82895. attribs.push(BABYLON.VertexBuffer.UVKind);
  82896. }
  82897. if (defines.UV2) {
  82898. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82899. }
  82900. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  82901. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  82902. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  82903. "vFogInfos", "vFogColor", "pointSize",
  82904. "vClipPlane", "mBones",
  82905. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  82906. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  82907. "shadowLevel", "alpha",
  82908. "vBackgroundCenter", "vReflectionControl",
  82909. "vDiffuseInfos", "diffuseMatrix",
  82910. ];
  82911. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  82912. var uniformBuffers = ["Material", "Scene"];
  82913. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  82914. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  82915. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  82916. uniformsNames: uniforms,
  82917. uniformBuffersNames: uniformBuffers,
  82918. samplers: samplers,
  82919. defines: defines,
  82920. maxSimultaneousLights: this._maxSimultaneousLights
  82921. });
  82922. var onCompiled = function (effect) {
  82923. if (_this.onCompiled) {
  82924. _this.onCompiled(effect);
  82925. }
  82926. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  82927. };
  82928. var join = defines.toString();
  82929. subMesh.setEffect(scene.getEngine().createEffect("background", {
  82930. attributes: attribs,
  82931. uniformsNames: uniforms,
  82932. uniformBuffersNames: uniformBuffers,
  82933. samplers: samplers,
  82934. defines: join,
  82935. fallbacks: fallbacks,
  82936. onCompiled: onCompiled,
  82937. onError: this.onError,
  82938. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  82939. }, engine), defines);
  82940. this.buildUniformLayout();
  82941. }
  82942. if (!subMesh.effect || !subMesh.effect.isReady()) {
  82943. return false;
  82944. }
  82945. defines._renderId = scene.getRenderId();
  82946. this._wasPreviouslyReady = true;
  82947. return true;
  82948. };
  82949. /**
  82950. * Build the uniform buffer used in the material.
  82951. */
  82952. BackgroundMaterial.prototype.buildUniformLayout = function () {
  82953. // Order is important !
  82954. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  82955. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  82956. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  82957. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  82958. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  82959. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  82960. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  82961. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  82962. this._uniformBuffer.addUniform("pointSize", 1);
  82963. this._uniformBuffer.addUniform("shadowLevel", 1);
  82964. this._uniformBuffer.addUniform("alpha", 1);
  82965. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  82966. this._uniformBuffer.addUniform("vReflectionControl", 4);
  82967. this._uniformBuffer.create();
  82968. };
  82969. /**
  82970. * Unbind the material.
  82971. */
  82972. BackgroundMaterial.prototype.unbind = function () {
  82973. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  82974. this._uniformBuffer.setTexture("diffuseSampler", null);
  82975. }
  82976. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  82977. this._uniformBuffer.setTexture("reflectionSampler", null);
  82978. }
  82979. _super.prototype.unbind.call(this);
  82980. };
  82981. /**
  82982. * Bind only the world matrix to the material.
  82983. * @param world The world matrix to bind.
  82984. */
  82985. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  82986. this._activeEffect.setMatrix("world", world);
  82987. };
  82988. /**
  82989. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  82990. * @param world The world matrix to bind.
  82991. * @param subMesh The submesh to bind for.
  82992. */
  82993. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  82994. var scene = this.getScene();
  82995. var defines = subMesh._materialDefines;
  82996. if (!defines) {
  82997. return;
  82998. }
  82999. var effect = subMesh.effect;
  83000. if (!effect) {
  83001. return;
  83002. }
  83003. this._activeEffect = effect;
  83004. // Matrices
  83005. this.bindOnlyWorldMatrix(world);
  83006. // Bones
  83007. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83008. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83009. if (mustRebind) {
  83010. this._uniformBuffer.bindToEffect(effect, "Material");
  83011. this.bindViewProjection(effect);
  83012. var reflectionTexture = this._reflectionTexture;
  83013. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83014. // Texture uniforms
  83015. if (scene.texturesEnabled) {
  83016. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83017. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83018. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83019. }
  83020. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83021. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83022. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83023. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83024. }
  83025. }
  83026. if (this.shadowLevel > 0) {
  83027. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83028. }
  83029. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83030. // Point size
  83031. if (this.pointsCloud) {
  83032. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83033. }
  83034. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83035. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83036. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83037. }
  83038. // Textures
  83039. if (scene.texturesEnabled) {
  83040. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83041. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83042. }
  83043. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83044. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83045. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83046. }
  83047. else if (!defines.REFLECTIONBLUR) {
  83048. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83049. }
  83050. else {
  83051. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83052. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83053. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83054. }
  83055. if (defines.REFLECTIONFRESNEL) {
  83056. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83057. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83058. }
  83059. }
  83060. }
  83061. // Clip plane
  83062. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83063. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83064. }
  83065. if (mustRebind || !this.isFrozen) {
  83066. if (scene.lightsEnabled) {
  83067. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83068. }
  83069. // View
  83070. this.bindView(effect);
  83071. // Fog
  83072. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83073. // image processing
  83074. this._imageProcessingConfiguration.bind(this._activeEffect);
  83075. }
  83076. this._uniformBuffer.update();
  83077. this._afterBind(mesh);
  83078. };
  83079. /**
  83080. * Dispose the material.
  83081. * @forceDisposeEffect Force disposal of the associated effect.
  83082. * @forceDisposeTextures Force disposal of the associated textures.
  83083. */
  83084. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83085. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83086. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83087. if (forceDisposeTextures) {
  83088. if (this.diffuseTexture) {
  83089. this.diffuseTexture.dispose();
  83090. }
  83091. if (this.reflectionTexture) {
  83092. this.reflectionTexture.dispose();
  83093. }
  83094. }
  83095. this._renderTargets.dispose();
  83096. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83097. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83098. }
  83099. _super.prototype.dispose.call(this, forceDisposeEffect);
  83100. };
  83101. /**
  83102. * Clones the material.
  83103. * @name The cloned name.
  83104. * @returns The cloned material.
  83105. */
  83106. BackgroundMaterial.prototype.clone = function (name) {
  83107. var _this = this;
  83108. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83109. };
  83110. /**
  83111. * Serializes the current material to its JSON representation.
  83112. * @returns The JSON representation.
  83113. */
  83114. BackgroundMaterial.prototype.serialize = function () {
  83115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83116. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83117. return serializationObject;
  83118. };
  83119. /**
  83120. * Gets the class name of the material
  83121. * @returns "BackgroundMaterial"
  83122. */
  83123. BackgroundMaterial.prototype.getClassName = function () {
  83124. return "BackgroundMaterial";
  83125. };
  83126. /**
  83127. * Parse a JSON input to create back a background material.
  83128. * @param source
  83129. * @param scene
  83130. * @param rootUrl
  83131. * @returns the instantiated BackgroundMaterial.
  83132. */
  83133. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83134. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83135. };
  83136. /**
  83137. * Standard reflectance value at parallel view angle.
  83138. */
  83139. BackgroundMaterial.standardReflectance0 = 0.05;
  83140. /**
  83141. * Standard reflectance value at grazing angle.
  83142. */
  83143. BackgroundMaterial.standardReflectance90 = 0.5;
  83144. __decorate([
  83145. BABYLON.serializeAsColor3()
  83146. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83147. __decorate([
  83148. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83149. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83150. __decorate([
  83151. BABYLON.serialize()
  83152. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83153. __decorate([
  83154. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83155. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83156. __decorate([
  83157. BABYLON.serializeAsColor3()
  83158. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83159. __decorate([
  83160. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83161. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83162. __decorate([
  83163. BABYLON.serialize()
  83164. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83165. __decorate([
  83166. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83167. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83168. __decorate([
  83169. BABYLON.serializeAsColor3()
  83170. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83171. __decorate([
  83172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83173. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83174. __decorate([
  83175. BABYLON.serialize()
  83176. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83177. __decorate([
  83178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83179. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83180. __decorate([
  83181. BABYLON.serializeAsTexture()
  83182. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83183. __decorate([
  83184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83185. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83186. __decorate([
  83187. BABYLON.serialize()
  83188. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83189. __decorate([
  83190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83191. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83192. __decorate([
  83193. BABYLON.serializeAsTexture()
  83194. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83195. __decorate([
  83196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83197. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83198. __decorate([
  83199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83200. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83201. __decorate([
  83202. BABYLON.serialize()
  83203. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83204. __decorate([
  83205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83206. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83207. __decorate([
  83208. BABYLON.serialize()
  83209. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83210. __decorate([
  83211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83212. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83213. __decorate([
  83214. BABYLON.serializeAsVector3()
  83215. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83216. __decorate([
  83217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83218. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83219. __decorate([
  83220. BABYLON.serialize()
  83221. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83222. __decorate([
  83223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83224. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83225. __decorate([
  83226. BABYLON.serialize()
  83227. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83228. __decorate([
  83229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83230. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83231. __decorate([
  83232. BABYLON.serialize()
  83233. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83234. __decorate([
  83235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83236. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83237. __decorate([
  83238. BABYLON.serialize()
  83239. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83240. __decorate([
  83241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83242. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83243. __decorate([
  83244. BABYLON.serialize()
  83245. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83246. __decorate([
  83247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83248. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83249. __decorate([
  83250. BABYLON.serialize()
  83251. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83252. __decorate([
  83253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83254. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83255. __decorate([
  83256. BABYLON.serialize()
  83257. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83258. __decorate([
  83259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83260. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83261. __decorate([
  83262. BABYLON.serialize()
  83263. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83264. __decorate([
  83265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83266. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83267. __decorate([
  83268. BABYLON.serialize()
  83269. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83270. __decorate([
  83271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83272. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83273. __decorate([
  83274. BABYLON.serializeAsImageProcessingConfiguration()
  83275. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83276. return BackgroundMaterial;
  83277. }(BABYLON.PushMaterial));
  83278. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83279. })(BABYLON || (BABYLON = {}));
  83280. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83281. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83282. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83283. s = arguments[i];
  83284. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83285. t[p] = s[p];
  83286. }
  83287. return t;
  83288. };
  83289. var BABYLON;
  83290. (function (BABYLON) {
  83291. /**
  83292. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  83293. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  83294. * It also helps with the default setup of your imageProcessing configuration.
  83295. */
  83296. var EnvironmentHelper = /** @class */ (function () {
  83297. /**
  83298. * constructor
  83299. * @param options
  83300. * @param scene The scene to add the material to
  83301. */
  83302. function EnvironmentHelper(options, scene) {
  83303. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  83304. this._scene = scene;
  83305. this._setupBackground();
  83306. this._setupImageProcessing();
  83307. }
  83308. /**
  83309. * Creates the default options for the helper.
  83310. */
  83311. EnvironmentHelper._getDefaultOptions = function () {
  83312. return {
  83313. createGround: true,
  83314. groundSize: 15,
  83315. groundTexture: this._groundTextureCDNUrl,
  83316. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83317. groundOpacity: 0.9,
  83318. enableGroundShadow: true,
  83319. groundShadowLevel: 0.5,
  83320. enableGroundMirror: false,
  83321. groundMirrorSizeRatio: 0.3,
  83322. groundMirrorBlurKernel: 64,
  83323. groundMirrorAmount: 1,
  83324. groundMirrorFresnelWeight: 1,
  83325. groundMirrorFallOffDistance: 0,
  83326. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  83327. groundYBias: 0.00001,
  83328. createSkybox: true,
  83329. skyboxSize: 20,
  83330. skyboxTexture: this._skyboxTextureCDNUrl,
  83331. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83332. backgroundYRotation: 0,
  83333. sizeAuto: true,
  83334. rootPosition: BABYLON.Vector3.Zero(),
  83335. setupImageProcessing: true,
  83336. environmentTexture: this._environmentTextureCDNUrl,
  83337. cameraExposure: 0.8,
  83338. cameraContrast: 1.2,
  83339. toneMappingEnabled: true,
  83340. };
  83341. };
  83342. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  83343. /**
  83344. * Gets the root mesh created by the helper.
  83345. */
  83346. get: function () {
  83347. return this._rootMesh;
  83348. },
  83349. enumerable: true,
  83350. configurable: true
  83351. });
  83352. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83353. /**
  83354. * Gets the skybox created by the helper.
  83355. */
  83356. get: function () {
  83357. return this._skybox;
  83358. },
  83359. enumerable: true,
  83360. configurable: true
  83361. });
  83362. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83363. /**
  83364. * Gets the skybox texture created by the helper.
  83365. */
  83366. get: function () {
  83367. return this._skyboxTexture;
  83368. },
  83369. enumerable: true,
  83370. configurable: true
  83371. });
  83372. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83373. /**
  83374. * Gets the skybox material created by the helper.
  83375. */
  83376. get: function () {
  83377. return this._skyboxMaterial;
  83378. },
  83379. enumerable: true,
  83380. configurable: true
  83381. });
  83382. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83383. /**
  83384. * Gets the ground mesh created by the helper.
  83385. */
  83386. get: function () {
  83387. return this._ground;
  83388. },
  83389. enumerable: true,
  83390. configurable: true
  83391. });
  83392. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83393. /**
  83394. * Gets the ground texture created by the helper.
  83395. */
  83396. get: function () {
  83397. return this._groundTexture;
  83398. },
  83399. enumerable: true,
  83400. configurable: true
  83401. });
  83402. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  83403. /**
  83404. * Gets the ground mirror created by the helper.
  83405. */
  83406. get: function () {
  83407. return this._groundMirror;
  83408. },
  83409. enumerable: true,
  83410. configurable: true
  83411. });
  83412. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  83413. /**
  83414. * Gets the ground mirror render list to helps pushing the meshes
  83415. * you wish in the ground reflection.
  83416. */
  83417. get: function () {
  83418. if (this._groundMirror) {
  83419. return this._groundMirror.renderList;
  83420. }
  83421. return null;
  83422. },
  83423. enumerable: true,
  83424. configurable: true
  83425. });
  83426. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  83427. /**
  83428. * Gets the ground material created by the helper.
  83429. */
  83430. get: function () {
  83431. return this._groundMaterial;
  83432. },
  83433. enumerable: true,
  83434. configurable: true
  83435. });
  83436. /**
  83437. * Updates the background according to the new options
  83438. * @param options
  83439. */
  83440. EnvironmentHelper.prototype.updateOptions = function (options) {
  83441. var newOptions = __assign({}, this._options, options);
  83442. if (this._ground && !newOptions.createGround) {
  83443. this._ground.dispose();
  83444. this._ground = null;
  83445. }
  83446. if (this._groundMaterial && !newOptions.createGround) {
  83447. this._groundMaterial.dispose();
  83448. this._groundMaterial = null;
  83449. }
  83450. if (this._groundTexture) {
  83451. if (this._options.groundTexture != newOptions.groundTexture) {
  83452. this._groundTexture.dispose();
  83453. this._groundTexture = null;
  83454. }
  83455. }
  83456. if (this._skybox && !newOptions.createSkybox) {
  83457. this._skybox.dispose();
  83458. this._skybox = null;
  83459. }
  83460. if (this._skyboxMaterial && !newOptions.createSkybox) {
  83461. this._skyboxMaterial.dispose();
  83462. this._skyboxMaterial = null;
  83463. }
  83464. if (this._skyboxTexture) {
  83465. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  83466. this._skyboxTexture.dispose();
  83467. this._skyboxTexture = null;
  83468. }
  83469. }
  83470. if (this._groundMirror && !newOptions.enableGroundMirror) {
  83471. this._groundMirror.dispose();
  83472. this._groundMirror = null;
  83473. }
  83474. if (this._scene.environmentTexture) {
  83475. if (this._options.environmentTexture != newOptions.environmentTexture) {
  83476. this._scene.environmentTexture.dispose();
  83477. }
  83478. }
  83479. this._options = newOptions;
  83480. this._setupBackground();
  83481. this._setupImageProcessing();
  83482. };
  83483. /**
  83484. * Sets the primary color of all the available elements.
  83485. * @param color
  83486. */
  83487. EnvironmentHelper.prototype.setMainColor = function (color) {
  83488. if (this.groundMaterial) {
  83489. this.groundMaterial.primaryColor = color;
  83490. }
  83491. if (this.skyboxMaterial) {
  83492. this.skyboxMaterial.primaryColor = color;
  83493. }
  83494. if (this.groundMirror) {
  83495. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  83496. }
  83497. };
  83498. /**
  83499. * Setup the image processing according to the specified options.
  83500. */
  83501. EnvironmentHelper.prototype._setupImageProcessing = function () {
  83502. if (this._options.setupImageProcessing) {
  83503. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  83504. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  83505. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  83506. this._setupEnvironmentTexture();
  83507. }
  83508. };
  83509. /**
  83510. * Setup the environment texture according to the specified options.
  83511. */
  83512. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  83513. if (this._scene.environmentTexture) {
  83514. return;
  83515. }
  83516. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  83517. this._scene.environmentTexture = this._options.environmentTexture;
  83518. return;
  83519. }
  83520. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  83521. this._scene.environmentTexture = environmentTexture;
  83522. };
  83523. /**
  83524. * Setup the background according to the specified options.
  83525. */
  83526. EnvironmentHelper.prototype._setupBackground = function () {
  83527. if (!this._rootMesh) {
  83528. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  83529. }
  83530. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  83531. var sceneSize = this._getSceneSize();
  83532. if (this._options.createGround) {
  83533. this._setupGround(sceneSize);
  83534. this._setupGroundMaterial();
  83535. this._setupGroundDiffuseTexture();
  83536. if (this._options.enableGroundMirror) {
  83537. this._setupGroundMirrorTexture(sceneSize);
  83538. }
  83539. this._setupMirrorInGroundMaterial();
  83540. }
  83541. if (this._options.createSkybox) {
  83542. this._setupSkybox(sceneSize);
  83543. this._setupSkyboxMaterial();
  83544. this._setupSkyboxReflectionTexture();
  83545. }
  83546. this._rootMesh.position.x = sceneSize.rootPosition.x;
  83547. this._rootMesh.position.z = sceneSize.rootPosition.z;
  83548. this._rootMesh.position.y = sceneSize.rootPosition.y;
  83549. };
  83550. /**
  83551. * Get the scene sizes according to the setup.
  83552. */
  83553. EnvironmentHelper.prototype._getSceneSize = function () {
  83554. var groundSize = this._options.groundSize;
  83555. var skyboxSize = this._options.skyboxSize;
  83556. var rootPosition = this._options.rootPosition;
  83557. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  83558. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83559. }
  83560. var sceneExtends = this._scene.getWorldExtends();
  83561. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  83562. if (this._options.sizeAuto) {
  83563. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  83564. this._scene.activeCamera.upperRadiusLimit) {
  83565. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  83566. skyboxSize = groundSize;
  83567. }
  83568. var sceneDiagonalLenght = sceneDiagonal.length();
  83569. if (sceneDiagonalLenght > groundSize) {
  83570. groundSize = sceneDiagonalLenght * 2;
  83571. skyboxSize = groundSize;
  83572. }
  83573. // 10 % bigger.
  83574. groundSize *= 1.1;
  83575. skyboxSize *= 1.5;
  83576. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  83577. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  83578. }
  83579. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83580. };
  83581. /**
  83582. * Setup the ground according to the specified options.
  83583. */
  83584. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  83585. var _this = this;
  83586. if (!this._ground) {
  83587. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  83588. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  83589. this._ground.parent = this._rootMesh;
  83590. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  83591. }
  83592. this._ground.receiveShadows = this._options.enableGroundShadow;
  83593. };
  83594. /**
  83595. * Setup the ground material according to the specified options.
  83596. */
  83597. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  83598. if (!this._groundMaterial) {
  83599. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  83600. }
  83601. this._groundMaterial.alpha = this._options.groundOpacity;
  83602. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  83603. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  83604. this._groundMaterial.primaryLevel = 1;
  83605. this._groundMaterial.primaryColor = this._options.groundColor;
  83606. this._groundMaterial.secondaryLevel = 0;
  83607. this._groundMaterial.tertiaryLevel = 0;
  83608. this._groundMaterial.useRGBColor = false;
  83609. this._groundMaterial.enableNoise = true;
  83610. if (this._ground) {
  83611. this._ground.material = this._groundMaterial;
  83612. }
  83613. };
  83614. /**
  83615. * Setup the ground diffuse texture according to the specified options.
  83616. */
  83617. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  83618. if (!this._groundMaterial) {
  83619. return;
  83620. }
  83621. if (this._groundTexture) {
  83622. return;
  83623. }
  83624. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  83625. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  83626. return;
  83627. }
  83628. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  83629. diffuseTexture.gammaSpace = false;
  83630. diffuseTexture.hasAlpha = true;
  83631. this._groundMaterial.diffuseTexture = diffuseTexture;
  83632. };
  83633. /**
  83634. * Setup the ground mirror texture according to the specified options.
  83635. */
  83636. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  83637. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83638. if (!this._groundMirror) {
  83639. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  83640. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  83641. this._groundMirror.anisotropicFilteringLevel = 1;
  83642. this._groundMirror.wrapU = wrapping;
  83643. this._groundMirror.wrapV = wrapping;
  83644. this._groundMirror.gammaSpace = false;
  83645. if (this._groundMirror.renderList) {
  83646. for (var i = 0; i < this._scene.meshes.length; i++) {
  83647. var mesh = this._scene.meshes[i];
  83648. if (mesh !== this._ground &&
  83649. mesh !== this._skybox &&
  83650. mesh !== this._rootMesh) {
  83651. this._groundMirror.renderList.push(mesh);
  83652. }
  83653. }
  83654. }
  83655. }
  83656. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  83657. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  83658. };
  83659. /**
  83660. * Setup the ground to receive the mirror texture.
  83661. */
  83662. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  83663. if (this._groundMaterial) {
  83664. this._groundMaterial.reflectionTexture = this._groundMirror;
  83665. this._groundMaterial.reflectionFresnel = true;
  83666. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  83667. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  83668. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  83669. }
  83670. };
  83671. /**
  83672. * Setup the skybox according to the specified options.
  83673. */
  83674. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  83675. var _this = this;
  83676. if (!this._skybox) {
  83677. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  83678. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  83679. }
  83680. this._skybox.parent = this._rootMesh;
  83681. };
  83682. /**
  83683. * Setup the skybox material according to the specified options.
  83684. */
  83685. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  83686. if (!this._skybox) {
  83687. return;
  83688. }
  83689. if (!this._skyboxMaterial) {
  83690. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  83691. }
  83692. this._skyboxMaterial.useRGBColor = false;
  83693. this._skyboxMaterial.primaryLevel = 1;
  83694. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  83695. this._skyboxMaterial.secondaryLevel = 0;
  83696. this._skyboxMaterial.tertiaryLevel = 0;
  83697. this._skyboxMaterial.enableNoise = true;
  83698. this._skybox.material = this._skyboxMaterial;
  83699. };
  83700. /**
  83701. * Setup the skybox reflection texture according to the specified options.
  83702. */
  83703. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  83704. if (!this._skyboxMaterial) {
  83705. return;
  83706. }
  83707. if (this._skyboxTexture) {
  83708. return;
  83709. }
  83710. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  83711. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83712. return;
  83713. }
  83714. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  83715. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  83716. this._skyboxTexture.gammaSpace = false;
  83717. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83718. };
  83719. /**
  83720. * Dispose all the elements created by the Helper.
  83721. */
  83722. EnvironmentHelper.prototype.dispose = function () {
  83723. if (this._groundMaterial) {
  83724. this._groundMaterial.dispose(true, true);
  83725. }
  83726. if (this._skyboxMaterial) {
  83727. this._skyboxMaterial.dispose(true, true);
  83728. }
  83729. this._rootMesh.dispose(false);
  83730. };
  83731. /**
  83732. * Default ground texture URL.
  83733. */
  83734. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  83735. /**
  83736. * Default skybox texture URL.
  83737. */
  83738. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  83739. /**
  83740. * Default environment texture URL.
  83741. */
  83742. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  83743. return EnvironmentHelper;
  83744. }());
  83745. BABYLON.EnvironmentHelper = EnvironmentHelper;
  83746. })(BABYLON || (BABYLON = {}));
  83747. //# sourceMappingURL=babylon.environmentHelper.js.map
  83748. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  83749. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  83750. globalObject["BABYLON"] = BABYLON;
  83751. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderPass = BABYLON.PostProcessRenderPass;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;
  83752. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderPass,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper };