babylon.engine.ts 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417
  1. module BABYLON {
  2. /**
  3. * Keeps track of all the buffer info used in engine.
  4. */
  5. class BufferPointer {
  6. public active: boolean;
  7. public index: number;
  8. public size: number;
  9. public type: number;
  10. public normalized: boolean;
  11. public stride: number;
  12. public offset: number;
  13. public buffer: WebGLBuffer;
  14. }
  15. /**
  16. * Interface for attribute information associated with buffer instanciation
  17. */
  18. export class InstancingAttributeInfo {
  19. /**
  20. * Index/offset of the attribute in the vertex shader
  21. */
  22. index: number;
  23. /**
  24. * size of the attribute, 1, 2, 3 or 4
  25. */
  26. attributeSize: number;
  27. /**
  28. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  29. * default is FLOAT
  30. */
  31. attribyteType: number;
  32. /**
  33. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  34. */
  35. normalized: boolean;
  36. /**
  37. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  38. */
  39. offset: number;
  40. /**
  41. * Name of the GLSL attribute, for debugging purpose only
  42. */
  43. attributeName: string;
  44. }
  45. /**
  46. * Define options used to create a render target texture
  47. */
  48. export class RenderTargetCreationOptions {
  49. /**
  50. * Specifies is mipmaps must be generated
  51. */
  52. generateMipMaps?: boolean;
  53. /** Specifies whether or not a depth should be allocated in the texture (true by default) */
  54. generateDepthBuffer?: boolean;
  55. /** Specifies whether or not a stencil should be allocated in the texture (false by default)*/
  56. generateStencilBuffer?: boolean;
  57. /** Defines texture type (int by default) */
  58. type?: number;
  59. /** Defines sampling mode (trilinear by default) */
  60. samplingMode?: number;
  61. /** Defines format (RGBA by default) */
  62. format?: number;
  63. }
  64. /**
  65. * Define options used to create a depth texture
  66. */
  67. export class DepthTextureCreationOptions {
  68. /** Specifies whether or not a stencil should be allocated in the texture */
  69. generateStencil?: boolean;
  70. /** Specifies whether or not bilinear filtering is enable on the texture */
  71. bilinearFiltering?: boolean;
  72. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  73. comparisonFunction?: number;
  74. /** Specifies if the created texture is a cube texture */
  75. isCube?: boolean;
  76. }
  77. /**
  78. * Class used to describe the capabilities of the engine relatively to the current browser
  79. */
  80. export class EngineCapabilities {
  81. /** Maximum textures units per fragment shader */
  82. public maxTexturesImageUnits: number;
  83. /** Maximum texture units per vertex shader */
  84. public maxVertexTextureImageUnits: number;
  85. /** Maximum textures units in the entire pipeline */
  86. public maxCombinedTexturesImageUnits: number;
  87. /** Maximum texture size */
  88. public maxTextureSize: number;
  89. /** Maximum cube texture size */
  90. public maxCubemapTextureSize: number;
  91. /** Maximum render texture size */
  92. public maxRenderTextureSize: number;
  93. /** Maximum number of vertex attributes */
  94. public maxVertexAttribs: number;
  95. /** Maximum number of varyings */
  96. public maxVaryingVectors: number;
  97. /** Maximum number of uniforms per vertex shader */
  98. public maxVertexUniformVectors: number;
  99. /** Maximum number of uniforms per fragment shader */
  100. public maxFragmentUniformVectors: number;
  101. /** Defines if standard derivates (dx/dy) are supported */
  102. public standardDerivatives: boolean;
  103. /** Defines if s3tc texture compression is supported */
  104. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  105. /** Defines if pvrtc texture compression is supported */
  106. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  107. /** Defines if etc1 texture compression is supported */
  108. public etc1: any; //WEBGL_compressed_texture_etc1;
  109. /** Defines if etc2 texture compression is supported */
  110. public etc2: any; //WEBGL_compressed_texture_etc;
  111. /** Defines if astc texture compression is supported */
  112. public astc: any; //WEBGL_compressed_texture_astc;
  113. /** Defines if float textures are supported */
  114. public textureFloat: boolean;
  115. /** Defines if vertex array objects are supported */
  116. public vertexArrayObject: boolean;
  117. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  118. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  119. /** Gets the maximum level of anisotropy supported */
  120. public maxAnisotropy: number;
  121. /** Defines if instancing is supported */
  122. public instancedArrays: boolean;
  123. /** Defines if 32 bits indices are supported */
  124. public uintIndices: boolean;
  125. /** Defines if high precision shaders are supported */
  126. public highPrecisionShaderSupported: boolean;
  127. /** Defines if depth reading in the fragment shader is supported */
  128. public fragmentDepthSupported: boolean;
  129. /** Defines if float texture linear filtering is supported*/
  130. public textureFloatLinearFiltering: boolean;
  131. /** Defines if rendering to float textures is supported */
  132. public textureFloatRender: boolean;
  133. /** Defines if half float textures are supported*/
  134. public textureHalfFloat: boolean;
  135. /** Defines if half float texture linear filtering is supported*/
  136. public textureHalfFloatLinearFiltering: boolean;
  137. /** Defines if rendering to half float textures is supported */
  138. public textureHalfFloatRender: boolean;
  139. /** Defines if textureLOD shader command is supported */
  140. public textureLOD: boolean;
  141. /** Defines if draw buffers extension is supported */
  142. public drawBuffersExtension: boolean;
  143. /** Defines if depth textures are supported */
  144. public depthTextureExtension: boolean;
  145. /** Defines if float color buffer are supported */
  146. public colorBufferFloat: boolean;
  147. /** Gets disjoint timer query extension (null if not supported) */
  148. public timerQuery: EXT_disjoint_timer_query;
  149. /** Defines if timestamp can be used with timer query */
  150. public canUseTimestampForTimerQuery: boolean;
  151. }
  152. /** Interface defining initialization parameters for Engine class */
  153. export interface EngineOptions extends WebGLContextAttributes {
  154. /**
  155. * Defines if the engine should no exceed a specified device ratio
  156. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  157. */
  158. limitDeviceRatio?: number;
  159. /**
  160. * Defines if webvr should be enabled automatically
  161. * @see http://doc.babylonjs.com/how_to/webvr_camera
  162. */
  163. autoEnableWebVR?: boolean;
  164. /**
  165. * Defines if webgl2 should be turned off even if supported
  166. * @see http://doc.babylonjs.com/features/webgl2
  167. */
  168. disableWebGL2Support?: boolean;
  169. /**
  170. * Defines if webaudio should be initialized as well
  171. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  172. */
  173. audioEngine?: boolean;
  174. /**
  175. * Defines if animations should run using a deterministic lock step
  176. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  177. */
  178. deterministicLockstep?: boolean;
  179. /** Defines the maximum steps to use with deterministic lock step mode */
  180. lockstepMaxSteps?: number;
  181. /**
  182. * Defines that engine should ignore context lost events
  183. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  184. */
  185. doNotHandleContextLost?: boolean;
  186. }
  187. /**
  188. * Defines the interface used by display changed events
  189. */
  190. export interface IDisplayChangedEventArgs {
  191. /** Gets the vrDisplay object (if any) */
  192. vrDisplay: Nullable<any>;
  193. /** Gets a boolean indicating if webVR is supported */
  194. vrSupported: boolean;
  195. }
  196. /**
  197. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  198. */
  199. export class Engine {
  200. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  201. public static ExceptionList = [
  202. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  203. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  204. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  205. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  206. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  207. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  208. ];
  209. /** Gets the list of created engines */
  210. public static Instances = new Array<Engine>();
  211. /**
  212. * Gets the latest created engine
  213. */
  214. public static get LastCreatedEngine(): Nullable<Engine> {
  215. if (Engine.Instances.length === 0) {
  216. return null;
  217. }
  218. return Engine.Instances[Engine.Instances.length - 1];
  219. }
  220. /**
  221. * Gets the latest created scene
  222. */
  223. public static get LastCreatedScene(): Nullable<Scene> {
  224. var lastCreatedEngine = Engine.LastCreatedEngine;
  225. if (!lastCreatedEngine) {
  226. return null;
  227. }
  228. if (lastCreatedEngine.scenes.length === 0) {
  229. return null;
  230. }
  231. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  232. }
  233. /**
  234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  235. * @param flag defines which part of the materials must be marked as dirty
  236. * @param predicate defines a predicate used to filter which materials should be affected
  237. */
  238. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  239. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  240. var engine = Engine.Instances[engineIndex];
  241. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  242. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  243. }
  244. }
  245. }
  246. /**
  247. * Hidden
  248. */
  249. public static _TextureLoaders: IInternalTextureLoader[] = [];
  250. // Const statics
  251. /** Defines that alpha blending is disabled */
  252. public static readonly ALPHA_DISABLE = 0;
  253. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  254. public static readonly ALPHA_ADD = 1;
  255. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  256. public static readonly ALPHA_COMBINE = 2;
  257. /** Defines that alpha blending to DEST - SRC * DEST */
  258. public static readonly ALPHA_SUBTRACT = 3;
  259. /** Defines that alpha blending to SRC * DEST */
  260. public static readonly ALPHA_MULTIPLY = 4;
  261. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  262. public static readonly ALPHA_MAXIMIZED = 5;
  263. /** Defines that alpha blending to SRC + DEST */
  264. public static readonly ALPHA_ONEONE = 6;
  265. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  266. public static readonly ALPHA_PREMULTIPLIED = 7;
  267. /**
  268. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  269. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  270. */
  271. public static readonly ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  272. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  273. public static readonly ALPHA_INTERPOLATE = 9;
  274. /**
  275. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  276. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  277. */
  278. public static readonly ALPHA_SCREENMODE = 10;
  279. /** Defines that the ressource is not delayed*/
  280. public static readonly DELAYLOADSTATE_NONE = 0;
  281. /** Defines that the ressource was successfully delay loaded */
  282. public static readonly DELAYLOADSTATE_LOADED = 1;
  283. /** Defines that the ressource is currently delay loading */
  284. public static readonly DELAYLOADSTATE_LOADING = 2;
  285. /** Defines that the ressource is delayed and has not started loading */
  286. public static readonly DELAYLOADSTATE_NOTLOADED = 4;
  287. // Depht or Stencil test Constants.
  288. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  289. public static readonly NEVER = 0x0200;
  290. /** 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 */
  291. public static readonly ALWAYS = 0x0207;
  292. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  293. public static readonly LESS = 0x0201;
  294. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  295. public static readonly EQUAL = 0x0202;
  296. /** 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 */
  297. public static readonly LEQUAL = 0x0203;
  298. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  299. public static readonly GREATER = 0x0204;
  300. /** 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 */
  301. public static readonly GEQUAL = 0x0206;
  302. /** 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 */
  303. public static readonly NOTEQUAL = 0x0205;
  304. // Stencil Actions Constants.
  305. /** Passed to stencilOperation to specify that stencil value must be kept */
  306. public static readonly KEEP = 0x1E00;
  307. /** Passed to stencilOperation to specify that stencil value must be replaced */
  308. public static readonly REPLACE = 0x1E01;
  309. /** Passed to stencilOperation to specify that stencil value must be incremented */
  310. public static readonly INCR = 0x1E02;
  311. /** Passed to stencilOperation to specify that stencil value must be decremented */
  312. public static readonly DECR = 0x1E03;
  313. /** Passed to stencilOperation to specify that stencil value must be inverted */
  314. public static readonly INVERT = 0x150A;
  315. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  316. public static readonly INCR_WRAP = 0x8507;
  317. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  318. public static readonly DECR_WRAP = 0x8508;
  319. /** Texture is not repeating outside of 0..1 UVs */
  320. public static readonly TEXTURE_CLAMP_ADDRESSMODE = 0;
  321. /** Texture is repeating outside of 0..1 UVs */
  322. public static readonly TEXTURE_WRAP_ADDRESSMODE = 1;
  323. /** Texture is repeating and mirrored */
  324. public static readonly TEXTURE_MIRROR_ADDRESSMODE = 2;
  325. /** ALPHA */
  326. public static readonly TEXTUREFORMAT_ALPHA = 0;
  327. /** LUMINANCE */
  328. public static readonly TEXTUREFORMAT_LUMINANCE = 1;
  329. /** LUMINANCE_ALPHA */
  330. public static readonly TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  331. /** RGB */
  332. public static readonly TEXTUREFORMAT_RGB = 4;
  333. /** RGBA */
  334. public static readonly TEXTUREFORMAT_RGBA = 5;
  335. /** RED */
  336. public static readonly TEXTUREFORMAT_RED = 6;
  337. /** RED (2nd reference) */
  338. public static readonly TEXTUREFORMAT_R = 6;
  339. /** RG */
  340. public static readonly TEXTUREFORMAT_RG = 7;
  341. /** RED_INTEGER */
  342. public static readonly TEXTUREFORMAT_RED_INTEGER = 8;
  343. /** RED_INTEGER (2nd reference) */
  344. public static readonly TEXTUREFORMAT_R_INTEGER = 8;
  345. /** RG_INTEGER */
  346. public static readonly TEXTUREFORMAT_RG_INTEGER = 9;
  347. /** RGB_INTEGER */
  348. public static readonly TEXTUREFORMAT_RGB_INTEGER = 10;
  349. /** RGBA_INTEGER */
  350. public static readonly TEXTUREFORMAT_RGBA_INTEGER = 11;
  351. /** UNSIGNED_BYTE */
  352. public static readonly TEXTURETYPE_UNSIGNED_BYTE = 0;
  353. /** UNSIGNED_BYTE (2nd reference) */
  354. public static readonly TEXTURETYPE_UNSIGNED_INT = 0;
  355. /** FLOAT */
  356. public static readonly TEXTURETYPE_FLOAT = 1;
  357. /** HALF_FLOAT */
  358. public static readonly TEXTURETYPE_HALF_FLOAT = 2;
  359. /** BYTE */
  360. public static readonly TEXTURETYPE_BYTE = 3;
  361. /** SHORT */
  362. public static readonly TEXTURETYPE_SHORT = 4;
  363. /** UNSIGNED_SHORT */
  364. public static readonly TEXTURETYPE_UNSIGNED_SHORT = 5;
  365. /** INT */
  366. public static readonly TEXTURETYPE_INT = 6;
  367. /** UNSIGNED_INT */
  368. public static readonly TEXTURETYPE_UNSIGNED_INTEGER = 7;
  369. /** UNSIGNED_SHORT_4_4_4_4 */
  370. public static readonly TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  371. /** UNSIGNED_SHORT_5_5_5_1 */
  372. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  373. /** UNSIGNED_SHORT_5_6_5 */
  374. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  375. /** UNSIGNED_INT_2_10_10_10_REV */
  376. public static readonly TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  377. /** UNSIGNED_INT_24_8 */
  378. public static readonly TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  379. /** UNSIGNED_INT_10F_11F_11F_REV */
  380. public static readonly TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  381. /** UNSIGNED_INT_5_9_9_9_REV */
  382. public static readonly TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  383. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  384. public static readonly TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  385. /** nearest is mag = nearest and min = nearest and mip = linear */
  386. public static readonly TEXTURE_NEAREST_SAMPLINGMODE = 1;
  387. /** Bilinear is mag = linear and min = linear and mip = nearest */
  388. public static readonly TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  389. /** Trilinear is mag = linear and min = linear and mip = linear */
  390. public static readonly TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  391. /** nearest is mag = nearest and min = nearest and mip = linear */
  392. public static readonly TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  393. /** Bilinear is mag = linear and min = linear and mip = nearest */
  394. public static readonly TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  395. /** Trilinear is mag = linear and min = linear and mip = linear */
  396. public static readonly TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  397. /** mag = nearest and min = nearest and mip = nearest */
  398. public static readonly TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  399. /** mag = nearest and min = linear and mip = nearest */
  400. public static readonly TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  401. /** mag = nearest and min = linear and mip = linear */
  402. public static readonly TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  403. /** mag = nearest and min = linear and mip = none */
  404. public static readonly TEXTURE_NEAREST_LINEAR = 7;
  405. /** mag = nearest and min = nearest and mip = none */
  406. public static readonly TEXTURE_NEAREST_NEAREST = 8;
  407. /** mag = linear and min = nearest and mip = nearest */
  408. public static readonly TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  409. /** mag = linear and min = nearest and mip = linear */
  410. public static readonly TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  411. /** mag = linear and min = linear and mip = none */
  412. public static readonly TEXTURE_LINEAR_LINEAR = 11;
  413. /** mag = linear and min = nearest and mip = none */
  414. public static readonly TEXTURE_LINEAR_NEAREST = 12;
  415. /** Explicit coordinates mode */
  416. public static readonly TEXTURE_EXPLICIT_MODE = 0;
  417. /** Spherical coordinates mode */
  418. public static readonly TEXTURE_SPHERICAL_MODE = 1;
  419. /** Planar coordinates mode */
  420. public static readonly TEXTURE_PLANAR_MODE = 2;
  421. /** Cubic coordinates mode */
  422. public static readonly TEXTURE_CUBIC_MODE = 3;
  423. /** Projection coordinates mode */
  424. public static readonly TEXTURE_PROJECTION_MODE = 4;
  425. /** Skybox coordinates mode */
  426. public static readonly TEXTURE_SKYBOX_MODE = 5;
  427. /** Inverse Cubic coordinates mode */
  428. public static readonly TEXTURE_INVCUBIC_MODE = 6;
  429. /** Equirectangular coordinates mode */
  430. public static readonly TEXTURE_EQUIRECTANGULAR_MODE = 7;
  431. /** Equirectangular Fixed coordinates mode */
  432. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  433. /** Equirectangular Fixed Mirrored coordinates mode */
  434. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  435. // Texture rescaling mode
  436. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  437. public static readonly SCALEMODE_FLOOR = 1;
  438. /** Defines that texture rescaling will look for the nearest power of 2 size */
  439. public static readonly SCALEMODE_NEAREST = 2;
  440. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  441. public static readonly SCALEMODE_CEILING = 3;
  442. /**
  443. * Returns the current version of the framework
  444. */
  445. public static get Version(): string {
  446. return "3.3.0-alpha.14";
  447. }
  448. // Updatable statics so stick with vars here
  449. /**
  450. * Gets or sets the epsilon value used by collision engine
  451. */
  452. public static CollisionsEpsilon = 0.001;
  453. /**
  454. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  455. */
  456. public static CodeRepository = "src/";
  457. /**
  458. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  459. */
  460. public static ShadersRepository = "src/Shaders/";
  461. // Public members
  462. /**
  463. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  464. */
  465. public forcePOTTextures = false;
  466. /**
  467. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  468. */
  469. public isFullscreen = false;
  470. /**
  471. * Gets a boolean indicating if the pointer is currently locked
  472. */
  473. public isPointerLock = false;
  474. /**
  475. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  476. */
  477. public cullBackFaces = true;
  478. /**
  479. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  480. */
  481. public renderEvenInBackground = true;
  482. /**
  483. * Gets or sets a boolean indicating that cache can be kept between frames
  484. */
  485. public preventCacheWipeBetweenFrames = false;
  486. /**
  487. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  488. **/
  489. public enableOfflineSupport = false;
  490. /**
  491. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  492. **/
  493. public disableManifestCheck = false;
  494. /**
  495. * Gets the list of created scenes
  496. */
  497. public scenes = new Array<Scene>();
  498. /**
  499. * Gets the list of created postprocesses
  500. */
  501. public postProcesses = new Array<PostProcess>();
  502. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  503. public validateShaderPrograms = false;
  504. // Observables
  505. /**
  506. * Observable event triggered each time the rendering canvas is resized
  507. */
  508. public onResizeObservable = new Observable<Engine>();
  509. /**
  510. * Observable event triggered each time the canvas loses focus
  511. */
  512. public onCanvasBlurObservable = new Observable<Engine>();
  513. /**
  514. * Observable event triggered each time the canvas gains focus
  515. */
  516. public onCanvasFocusObservable = new Observable<Engine>();
  517. /**
  518. * Observable event triggered each time the canvas receives pointerout event
  519. */
  520. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  521. /**
  522. * Observable event triggered before each texture is initialized
  523. */
  524. public onBeforeTextureInitObservable = new Observable<Texture>();
  525. //WebVR
  526. private _vrDisplay: any = undefined;
  527. private _vrSupported: boolean = false;
  528. private _oldSize: Size;
  529. private _oldHardwareScaleFactor: number;
  530. private _vrExclusivePointerMode = false;
  531. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  532. /**
  533. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  534. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  535. */
  536. public get isInVRExclusivePointerMode(): boolean {
  537. return this._vrExclusivePointerMode;
  538. }
  539. // Uniform buffers list
  540. /**
  541. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  542. */
  543. public disableUniformBuffers = false;
  544. /** @hidden */
  545. public _uniformBuffers = new Array<UniformBuffer>();
  546. /**
  547. * Gets a boolean indicating that the engine supports uniform buffers
  548. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  549. */
  550. public get supportsUniformBuffers(): boolean {
  551. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  552. }
  553. // Observables
  554. /**
  555. * Observable raised when the engine begins a new frame
  556. */
  557. public onBeginFrameObservable = new Observable<Engine>();
  558. /**
  559. * Observable raised when the engine ends the current frame
  560. */
  561. public onEndFrameObservable = new Observable<Engine>();
  562. /**
  563. * Observable raised when the engine is about to compile a shader
  564. */
  565. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  566. /**
  567. * Observable raised when the engine has jsut compiled a shader
  568. */
  569. public onAfterShaderCompilationObservable = new Observable<Engine>();
  570. // Private Members
  571. /** @hidden */
  572. public _gl: WebGLRenderingContext;
  573. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  574. private _windowIsBackground = false;
  575. protected _webGLVersion = 1.0;
  576. /**
  577. * Gets a boolean indicating that only power of 2 textures are supported
  578. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  579. */
  580. public get needPOTTextures(): boolean {
  581. return this._webGLVersion < 2 || this.forcePOTTextures;
  582. }
  583. /** @hidden */
  584. public _badOS = false;
  585. /** @hidden */
  586. public _badDesktopOS = false;
  587. /**
  588. * Gets or sets a value indicating if we want to disable texture binding optmization.
  589. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  590. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  591. */
  592. public disableTextureBindingOptimization = false;
  593. /**
  594. * Gets the audio engine
  595. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  596. * @ignorenaming
  597. */
  598. public static audioEngine: AudioEngine;
  599. // Focus
  600. private _onFocus: () => void;
  601. private _onBlur: () => void;
  602. private _onCanvasPointerOut: (event: PointerEvent) => void;
  603. private _onCanvasBlur: () => void;
  604. private _onCanvasFocus: () => void;
  605. private _onFullscreenChange: () => void;
  606. private _onPointerLockChange: () => void;
  607. private _onVRDisplayPointerRestricted: () => void;
  608. private _onVRDisplayPointerUnrestricted: () => void;
  609. // VRDisplay connection
  610. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  611. private _onVrDisplayDisconnect: Nullable<() => void>;
  612. private _onVrDisplayPresentChange: Nullable<() => void>;
  613. /**
  614. * Observable signaled when VR display mode changes
  615. */
  616. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  617. /**
  618. * Observable signaled when VR request present is complete
  619. */
  620. public onVRRequestPresentComplete = new Observable<boolean>();
  621. /**
  622. * Observable signaled when VR request present starts
  623. */
  624. public onVRRequestPresentStart = new Observable<Engine>();
  625. private _hardwareScalingLevel: number;
  626. /** @hidden */
  627. protected _caps: EngineCapabilities;
  628. private _pointerLockRequested: boolean;
  629. private _isStencilEnable: boolean;
  630. private _colorWrite = true;
  631. private _loadingScreen: ILoadingScreen;
  632. /** @hidden */
  633. public _drawCalls = new PerfCounter();
  634. /** @hidden */
  635. public _textureCollisions = new PerfCounter();
  636. private _glVersion: string;
  637. private _glRenderer: string;
  638. private _glVendor: string;
  639. private _videoTextureSupported: boolean;
  640. private _renderingQueueLaunched = false;
  641. private _activeRenderLoops = new Array<() => void>();
  642. // Deterministic lockstepMaxSteps
  643. private _deterministicLockstep: boolean = false;
  644. private _lockstepMaxSteps: number = 4;
  645. // Lost context
  646. /**
  647. * Observable signaled when a context lost event is raised
  648. */
  649. public onContextLostObservable = new Observable<Engine>();
  650. /**
  651. * Observable signaled when a context restored event is raised
  652. */
  653. public onContextRestoredObservable = new Observable<Engine>();
  654. private _onContextLost: (evt: Event) => void;
  655. private _onContextRestored: (evt: Event) => void;
  656. private _contextWasLost = false;
  657. private _doNotHandleContextLost = false;
  658. /**
  659. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  660. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  661. */
  662. public get doNotHandleContextLost(): boolean {
  663. return this._doNotHandleContextLost;
  664. }
  665. public set doNotHandleContextLost(value: boolean) {
  666. this._doNotHandleContextLost = value;
  667. }
  668. // FPS
  669. private _performanceMonitor = new PerformanceMonitor();
  670. private _fps = 60;
  671. private _deltaTime = 0;
  672. /**
  673. * Turn this value on if you want to pause FPS computation when in background
  674. */
  675. public disablePerformanceMonitorInBackground = false;
  676. /**
  677. * Gets the performance monitor attached to this engine
  678. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  679. */
  680. public get performanceMonitor(): PerformanceMonitor {
  681. return this._performanceMonitor;
  682. }
  683. // States
  684. /** @hidden */
  685. protected _depthCullingState = new _DepthCullingState();
  686. /** @hidden */
  687. protected _stencilState = new _StencilState();
  688. /** @hidden */
  689. protected _alphaState = new _AlphaState();
  690. /** @hidden */
  691. protected _alphaMode = Engine.ALPHA_DISABLE;
  692. // Cache
  693. protected _internalTexturesCache = new Array<InternalTexture>();
  694. /** @hidden */
  695. protected _activeChannel = 0;
  696. private _currentTextureChannel = -1;
  697. /** @hidden */
  698. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  699. /** @hidden */
  700. protected _currentEffect: Nullable<Effect>;
  701. /** @hidden */
  702. protected _currentProgram: Nullable<WebGLProgram>;
  703. private _compiledEffects: { [key: string]: Effect } = {}
  704. private _vertexAttribArraysEnabled: boolean[] = [];
  705. /** @hidden */
  706. protected _cachedViewport: Nullable<Viewport>;
  707. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  708. /** @hidden */
  709. protected _cachedVertexBuffers: any;
  710. /** @hidden */
  711. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  712. /** @hidden */
  713. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  714. /** @hidden */
  715. protected _currentRenderTarget: Nullable<InternalTexture>;
  716. private _uintIndicesCurrentlySet = false;
  717. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  718. /** @hidden */
  719. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  720. private _currentBufferPointers = new Array<BufferPointer>();
  721. private _currentInstanceLocations = new Array<number>();
  722. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  723. private _textureUnits: Int32Array;
  724. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  725. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  726. private _workingCanvas: Nullable<HTMLCanvasElement>;
  727. private _workingContext: Nullable<CanvasRenderingContext2D>;
  728. private _rescalePostProcess: PassPostProcess;
  729. private _dummyFramebuffer: WebGLFramebuffer;
  730. private _externalData: StringDictionary<Object>;
  731. private _bindedRenderFunction: any;
  732. private _vaoRecordInProgress = false;
  733. private _mustWipeVertexAttributes = false;
  734. private _emptyTexture: Nullable<InternalTexture>;
  735. private _emptyCubeTexture: Nullable<InternalTexture>;
  736. private _emptyTexture3D: Nullable<InternalTexture>;
  737. private _frameHandler: number;
  738. private _nextFreeTextureSlots = new Array<number>();
  739. private _maxSimultaneousTextures = 0;
  740. private _activeRequests = new Array<IFileRequest>();
  741. // Hardware supported Compressed Textures
  742. private _texturesSupported = new Array<string>();
  743. private _textureFormatInUse: Nullable<string>;
  744. /**
  745. * Gets the list of texture formats supported
  746. */
  747. public get texturesSupported(): Array<string> {
  748. return this._texturesSupported;
  749. }
  750. /**
  751. * Gets the list of texture formats in use
  752. */
  753. public get textureFormatInUse(): Nullable<string> {
  754. return this._textureFormatInUse;
  755. }
  756. /**
  757. * Gets the current viewport
  758. */
  759. public get currentViewport(): Nullable<Viewport> {
  760. return this._cachedViewport;
  761. }
  762. /**
  763. * Gets the default empty texture
  764. */
  765. public get emptyTexture(): InternalTexture {
  766. if (!this._emptyTexture) {
  767. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  768. }
  769. return this._emptyTexture;
  770. }
  771. /**
  772. * Gets the default empty 3D texture
  773. */
  774. public get emptyTexture3D(): InternalTexture {
  775. if (!this._emptyTexture3D) {
  776. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  777. }
  778. return this._emptyTexture3D;
  779. }
  780. /**
  781. * Gets the default empty cube texture
  782. */
  783. public get emptyCubeTexture(): InternalTexture {
  784. if (!this._emptyCubeTexture) {
  785. var faceData = new Uint8Array(4);
  786. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  787. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  788. }
  789. return this._emptyCubeTexture;
  790. }
  791. /**
  792. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  793. */
  794. public readonly premultipliedAlpha: boolean = true;
  795. /**
  796. * Creates a new engine
  797. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  798. * @param antialias defines enable antialiasing (default: false)
  799. * @param options defines further options to be sent to the getContext() function
  800. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  801. */
  802. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  803. // Register promises
  804. PromisePolyfill.Apply();
  805. let canvas: Nullable<HTMLCanvasElement> = null;
  806. Engine.Instances.push(this);
  807. if (!canvasOrContext) {
  808. return;
  809. }
  810. options = options || {};
  811. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  812. canvas = <HTMLCanvasElement>canvasOrContext;
  813. this._renderingCanvas = canvas;
  814. if (antialias != null) {
  815. options.antialias = antialias;
  816. }
  817. if (options.deterministicLockstep === undefined) {
  818. options.deterministicLockstep = false;
  819. }
  820. if (options.lockstepMaxSteps === undefined) {
  821. options.lockstepMaxSteps = 4;
  822. }
  823. if (options.preserveDrawingBuffer === undefined) {
  824. options.preserveDrawingBuffer = false;
  825. }
  826. if (options.audioEngine === undefined) {
  827. options.audioEngine = true;
  828. }
  829. if (options.stencil === undefined) {
  830. options.stencil = true;
  831. }
  832. if (options.premultipliedAlpha === false) {
  833. this.premultipliedAlpha = false;
  834. }
  835. this._deterministicLockstep = options.deterministicLockstep;
  836. this._lockstepMaxSteps = options.lockstepMaxSteps;
  837. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  838. // Exceptions
  839. if (navigator && navigator.userAgent) {
  840. let ua = navigator.userAgent;
  841. for (var exception of Engine.ExceptionList) {
  842. let key = exception.key;
  843. let targets = exception.targets;
  844. if (ua.indexOf(key) > -1) {
  845. if (exception.capture && exception.captureConstraint) {
  846. let capture = exception.capture;
  847. let constraint = exception.captureConstraint;
  848. let regex = new RegExp(capture);
  849. let matches = regex.exec(ua);
  850. if (matches && matches.length > 0) {
  851. let capturedValue = parseInt(matches[matches.length - 1]);
  852. if (capturedValue >= constraint) {
  853. continue;
  854. }
  855. }
  856. }
  857. for (var target of targets) {
  858. switch (target) {
  859. case "uniformBuffer":
  860. this.disableUniformBuffers = true;
  861. break;
  862. case "textureBindingOptimization":
  863. this.disableTextureBindingOptimization = true;
  864. break;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. // GL
  871. if (!options.disableWebGL2Support) {
  872. try {
  873. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  874. if (this._gl) {
  875. this._webGLVersion = 2.0;
  876. }
  877. } catch (e) {
  878. // Do nothing
  879. }
  880. }
  881. if (!this._gl) {
  882. if (!canvas) {
  883. throw new Error("The provided canvas is null or undefined.");
  884. }
  885. try {
  886. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  887. } catch (e) {
  888. throw new Error("WebGL not supported");
  889. }
  890. }
  891. if (!this._gl) {
  892. throw new Error("WebGL not supported");
  893. }
  894. this._onCanvasFocus = () => {
  895. this.onCanvasFocusObservable.notifyObservers(this);
  896. }
  897. this._onCanvasBlur = () => {
  898. this.onCanvasBlurObservable.notifyObservers(this);
  899. }
  900. canvas.addEventListener("focus", this._onCanvasFocus);
  901. canvas.addEventListener("blur", this._onCanvasBlur);
  902. this._onBlur = () => {
  903. if (this.disablePerformanceMonitorInBackground) {
  904. this._performanceMonitor.disable();
  905. }
  906. this._windowIsBackground = true;
  907. };
  908. this._onFocus = () => {
  909. if (this.disablePerformanceMonitorInBackground) {
  910. this._performanceMonitor.enable();
  911. }
  912. this._windowIsBackground = false;
  913. };
  914. this._onCanvasPointerOut = (ev) => {
  915. this.onCanvasPointerOutObservable.notifyObservers(ev);
  916. };
  917. window.addEventListener("blur", this._onBlur);
  918. window.addEventListener("focus", this._onFocus);
  919. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  920. // Context lost
  921. if (!this._doNotHandleContextLost) {
  922. this._onContextLost = (evt: Event) => {
  923. evt.preventDefault();
  924. this._contextWasLost = true;
  925. Tools.Warn("WebGL context lost.");
  926. this.onContextLostObservable.notifyObservers(this);
  927. };
  928. this._onContextRestored = (evt: Event) => {
  929. // Adding a timeout to avoid race condition at browser level
  930. setTimeout(() => {
  931. // Rebuild gl context
  932. this._initGLContext();
  933. // Rebuild effects
  934. this._rebuildEffects();
  935. // Rebuild textures
  936. this._rebuildInternalTextures();
  937. // Rebuild buffers
  938. this._rebuildBuffers();
  939. // Cache
  940. this.wipeCaches(true);
  941. Tools.Warn("WebGL context successfully restored.");
  942. this.onContextRestoredObservable.notifyObservers(this);
  943. this._contextWasLost = false;
  944. }, 0);
  945. };
  946. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  947. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  948. }
  949. } else {
  950. this._gl = <WebGLRenderingContext>canvasOrContext;
  951. this._renderingCanvas = this._gl.canvas
  952. if (this._gl.renderbufferStorageMultisample) {
  953. this._webGLVersion = 2.0;
  954. }
  955. options.stencil = this._gl.getContextAttributes().stencil;
  956. }
  957. // Viewport
  958. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  959. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  960. this.resize();
  961. this._isStencilEnable = options.stencil ? true : false;
  962. this._initGLContext();
  963. if (canvas) {
  964. // Fullscreen
  965. this._onFullscreenChange = () => {
  966. if (document.fullscreen !== undefined) {
  967. this.isFullscreen = document.fullscreen;
  968. } else if (document.mozFullScreen !== undefined) {
  969. this.isFullscreen = document.mozFullScreen;
  970. } else if (document.webkitIsFullScreen !== undefined) {
  971. this.isFullscreen = document.webkitIsFullScreen;
  972. } else if (document.msIsFullScreen !== undefined) {
  973. this.isFullscreen = document.msIsFullScreen;
  974. }
  975. // Pointer lock
  976. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  977. canvas.requestPointerLock = canvas.requestPointerLock ||
  978. canvas.msRequestPointerLock ||
  979. canvas.mozRequestPointerLock ||
  980. canvas.webkitRequestPointerLock;
  981. if (canvas.requestPointerLock) {
  982. canvas.requestPointerLock();
  983. }
  984. }
  985. };
  986. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  987. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  988. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  989. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  990. // Pointer lock
  991. this._onPointerLockChange = () => {
  992. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  993. document.webkitPointerLockElement === canvas ||
  994. document.msPointerLockElement === canvas ||
  995. document.pointerLockElement === canvas
  996. );
  997. };
  998. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  999. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1000. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1001. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1002. this._onVRDisplayPointerRestricted = () => {
  1003. if (canvas) {
  1004. canvas.requestPointerLock();
  1005. }
  1006. }
  1007. this._onVRDisplayPointerUnrestricted = () => {
  1008. document.exitPointerLock();
  1009. }
  1010. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1011. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1012. }
  1013. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  1014. Engine.audioEngine = new AudioEngine();
  1015. }
  1016. // Prepare buffer pointers
  1017. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1018. this._currentBufferPointers[i] = new BufferPointer();
  1019. }
  1020. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1021. // Load WebVR Devices
  1022. if (options.autoEnableWebVR) {
  1023. this.initWebVR();
  1024. }
  1025. // Detect if we are running on a faulty buggy OS.
  1026. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1027. // Detect if we are running on a faulty buggy desktop OS.
  1028. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1029. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  1030. this.enableOfflineSupport = (Database !== undefined);
  1031. }
  1032. private _rebuildInternalTextures(): void {
  1033. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1034. for (var internalTexture of currentState) {
  1035. internalTexture._rebuild();
  1036. }
  1037. }
  1038. private _rebuildEffects(): void {
  1039. for (var key in this._compiledEffects) {
  1040. let effect = <Effect>this._compiledEffects[key];
  1041. effect._prepareEffect();
  1042. }
  1043. Effect.ResetCache();
  1044. }
  1045. private _rebuildBuffers(): void {
  1046. // Index / Vertex
  1047. for (var scene of this.scenes) {
  1048. scene.resetCachedMaterial();
  1049. scene._rebuildGeometries();
  1050. scene._rebuildTextures();
  1051. }
  1052. // Uniforms
  1053. for (var uniformBuffer of this._uniformBuffers) {
  1054. uniformBuffer._rebuild();
  1055. }
  1056. }
  1057. private _initGLContext(): void {
  1058. // Caps
  1059. this._caps = new EngineCapabilities();
  1060. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1061. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1062. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1063. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1064. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1065. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1066. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1067. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1068. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1069. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1070. // Infos
  1071. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1072. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1073. if (rendererInfo != null) {
  1074. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1075. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1076. }
  1077. if (!this._glVendor) {
  1078. this._glVendor = "Unknown vendor";
  1079. }
  1080. if (!this._glRenderer) {
  1081. this._glRenderer = "Unknown renderer";
  1082. }
  1083. // Constants
  1084. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1085. if (this._gl.RGBA16F !== 0x881A) {
  1086. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1087. }
  1088. if (this._gl.RGBA32F !== 0x8814) {
  1089. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1090. }
  1091. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1092. this._gl.DEPTH24_STENCIL8 = 35056;
  1093. }
  1094. // Extensions
  1095. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1096. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1097. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1098. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1099. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1100. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1101. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1102. 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');
  1103. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1104. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1105. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1106. this._caps.highPrecisionShaderSupported = true;
  1107. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1108. if (this._caps.timerQuery) {
  1109. if (this._webGLVersion === 1) {
  1110. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1111. }
  1112. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1113. }
  1114. // Checks if some of the format renders first to allow the use of webgl inspector.
  1115. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1116. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1117. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1118. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true: false;
  1119. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true: false;
  1120. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1121. if (this._webGLVersion > 1) {
  1122. this._gl.HALF_FLOAT_OES = 0x140B;
  1123. }
  1124. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1125. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true: false;
  1126. // Draw buffers
  1127. if (this._webGLVersion > 1) {
  1128. this._caps.drawBuffersExtension = true;
  1129. } else {
  1130. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1131. if (drawBuffersExtension !== null) {
  1132. this._caps.drawBuffersExtension = true;
  1133. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1134. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1135. for (var i = 0; i < 16; i++) {
  1136. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1137. }
  1138. } else {
  1139. this._caps.drawBuffersExtension = false;
  1140. }
  1141. }
  1142. // Depth Texture
  1143. if (this._webGLVersion > 1) {
  1144. this._caps.depthTextureExtension = true;
  1145. } else {
  1146. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1147. if (depthTextureExtension != null) {
  1148. this._caps.depthTextureExtension = true;
  1149. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1150. }
  1151. }
  1152. // Vertex array object
  1153. if (this._webGLVersion > 1) {
  1154. this._caps.vertexArrayObject = true;
  1155. } else {
  1156. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1157. if (vertexArrayObjectExtension != null) {
  1158. this._caps.vertexArrayObject = true;
  1159. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1160. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1161. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1162. } else {
  1163. this._caps.vertexArrayObject = false;
  1164. }
  1165. }
  1166. // Instances count
  1167. if (this._webGLVersion > 1) {
  1168. this._caps.instancedArrays = true;
  1169. } else {
  1170. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1171. if (instanceExtension != null) {
  1172. this._caps.instancedArrays = true;
  1173. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1174. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1175. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1176. } else {
  1177. this._caps.instancedArrays = false;
  1178. }
  1179. }
  1180. // Intelligently add supported compressed formats in order to check for.
  1181. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1182. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1183. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1184. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1185. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1186. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1187. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1188. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1189. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1190. if (this._gl.getShaderPrecisionFormat) {
  1191. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1192. if (highp) {
  1193. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1194. }
  1195. }
  1196. // Depth buffer
  1197. this.setDepthBuffer(true);
  1198. this.setDepthFunctionToLessOrEqual();
  1199. this.setDepthWrite(true);
  1200. // Texture maps
  1201. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1202. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1203. this._nextFreeTextureSlots.push(slot);
  1204. }
  1205. }
  1206. /**
  1207. * Gets version of the current webGL context
  1208. */
  1209. public get webGLVersion(): number {
  1210. return this._webGLVersion;
  1211. }
  1212. /**
  1213. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1214. */
  1215. public get isStencilEnable(): boolean {
  1216. return this._isStencilEnable;
  1217. }
  1218. private _prepareWorkingCanvas(): void {
  1219. if (this._workingCanvas) {
  1220. return;
  1221. }
  1222. this._workingCanvas = document.createElement("canvas");
  1223. let context = this._workingCanvas.getContext("2d");
  1224. if (context) {
  1225. this._workingContext = context;
  1226. }
  1227. }
  1228. /**
  1229. * Reset the texture cache to empty state
  1230. */
  1231. public resetTextureCache() {
  1232. for (var key in this._boundTexturesCache) {
  1233. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1234. continue;
  1235. }
  1236. let boundTexture = this._boundTexturesCache[key];
  1237. if (boundTexture) {
  1238. this._removeDesignatedSlot(boundTexture);
  1239. }
  1240. this._boundTexturesCache[key] = null;
  1241. }
  1242. if (!this.disableTextureBindingOptimization) {
  1243. this._nextFreeTextureSlots = [];
  1244. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1245. this._nextFreeTextureSlots.push(slot);
  1246. }
  1247. }
  1248. this._currentTextureChannel = -1;
  1249. }
  1250. /**
  1251. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1252. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1253. * @returns true if engine is in deterministic lock step mode
  1254. */
  1255. public isDeterministicLockStep(): boolean {
  1256. return this._deterministicLockstep;
  1257. }
  1258. /**
  1259. * Gets the max steps when engine is running in deterministic lock step
  1260. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1261. * @returns the max steps
  1262. */
  1263. public getLockstepMaxSteps(): number {
  1264. return this._lockstepMaxSteps;
  1265. }
  1266. /**
  1267. * Gets an object containing information about the current webGL context
  1268. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1269. */
  1270. public getGlInfo() {
  1271. return {
  1272. vendor: this._glVendor,
  1273. renderer: this._glRenderer,
  1274. version: this._glVersion
  1275. }
  1276. }
  1277. /**
  1278. * Gets current aspect ratio
  1279. * @param camera defines the camera to use to get the aspect ratio
  1280. * @param useScreen defines if screen size must be used (or the current render target if any)
  1281. * @returns a number defining the aspect ratio
  1282. */
  1283. public getAspectRatio(camera: Camera, useScreen = false): number {
  1284. var viewport = camera.viewport;
  1285. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1286. }
  1287. /**
  1288. * Gets current screen aspect ratio
  1289. * @returns a number defining the aspect ratio
  1290. */
  1291. public getScreenAspectRatio(): number {
  1292. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1293. }
  1294. /**
  1295. * Gets the current render width
  1296. * @param useScreen defines if screen size must be used (or the current render target if any)
  1297. * @returns a number defining the current render width
  1298. */
  1299. public getRenderWidth(useScreen = false): number {
  1300. if (!useScreen && this._currentRenderTarget) {
  1301. return this._currentRenderTarget.width;
  1302. }
  1303. return this._gl.drawingBufferWidth;
  1304. }
  1305. /**
  1306. * Gets the current render height
  1307. * @param useScreen defines if screen size must be used (or the current render target if any)
  1308. * @returns a number defining the current render height
  1309. */
  1310. public getRenderHeight(useScreen = false): number {
  1311. if (!useScreen && this._currentRenderTarget) {
  1312. return this._currentRenderTarget.height;
  1313. }
  1314. return this._gl.drawingBufferHeight;
  1315. }
  1316. /**
  1317. * Gets the HTML canvas attached with the current webGL context
  1318. * @returns a HTML canvas
  1319. */
  1320. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1321. return this._renderingCanvas;
  1322. }
  1323. /**
  1324. * Gets the client rect of the HTML canvas attached with the current webGL context
  1325. * @returns a client rectanglee
  1326. */
  1327. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1328. if (!this._renderingCanvas) {
  1329. return null;
  1330. }
  1331. return this._renderingCanvas.getBoundingClientRect();
  1332. }
  1333. /**
  1334. * Defines the hardware scaling level.
  1335. * By default the hardware scaling level is computed from the window device ratio.
  1336. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1337. * @param level defines the level to use
  1338. */
  1339. public setHardwareScalingLevel(level: number): void {
  1340. this._hardwareScalingLevel = level;
  1341. this.resize();
  1342. }
  1343. /**
  1344. * Gets the current hardware scaling level.
  1345. * By default the hardware scaling level is computed from the window device ratio.
  1346. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1347. * @returns a number indicating the current hardware scaling level
  1348. */
  1349. public getHardwareScalingLevel(): number {
  1350. return this._hardwareScalingLevel;
  1351. }
  1352. /**
  1353. * Gets the list of loaded textures
  1354. * @returns an array containing all loaded textures
  1355. */
  1356. public getLoadedTexturesCache(): InternalTexture[] {
  1357. return this._internalTexturesCache;
  1358. }
  1359. /**
  1360. * Gets the object containing all engine capabilities
  1361. * @returns the EngineCapabilities object
  1362. */
  1363. public getCaps(): EngineCapabilities {
  1364. return this._caps;
  1365. }
  1366. /** @hidden */
  1367. public get drawCalls(): number {
  1368. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1369. return 0;
  1370. }
  1371. /** @hidden */
  1372. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1373. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1374. return null;
  1375. }
  1376. /**
  1377. * Gets the current depth function
  1378. * @returns a number defining the depth function
  1379. */
  1380. public getDepthFunction(): Nullable<number> {
  1381. return this._depthCullingState.depthFunc;
  1382. }
  1383. /**
  1384. * Sets the current depth function
  1385. * @param depthFunc defines the function to use
  1386. */
  1387. public setDepthFunction(depthFunc: number) {
  1388. this._depthCullingState.depthFunc = depthFunc;
  1389. }
  1390. /**
  1391. * Sets the current depth function to GREATER
  1392. */
  1393. public setDepthFunctionToGreater(): void {
  1394. this._depthCullingState.depthFunc = this._gl.GREATER;
  1395. }
  1396. /**
  1397. * Sets the current depth function to GEQUAL
  1398. */
  1399. public setDepthFunctionToGreaterOrEqual(): void {
  1400. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1401. }
  1402. /**
  1403. * Sets the current depth function to LESS
  1404. */
  1405. public setDepthFunctionToLess(): void {
  1406. this._depthCullingState.depthFunc = this._gl.LESS;
  1407. }
  1408. /**
  1409. * Sets the current depth function to LEQUAL
  1410. */
  1411. public setDepthFunctionToLessOrEqual(): void {
  1412. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1413. }
  1414. /**
  1415. * Gets a boolean indicating if stencil buffer is enabled
  1416. * @returns the current stencil buffer state
  1417. */
  1418. public getStencilBuffer(): boolean {
  1419. return this._stencilState.stencilTest;
  1420. }
  1421. /**
  1422. * Enable or disable the stencil buffer
  1423. * @param enable defines if the stencil buffer must be enabled or disabled
  1424. */
  1425. public setStencilBuffer(enable: boolean): void {
  1426. this._stencilState.stencilTest = enable;
  1427. }
  1428. /**
  1429. * Gets the current stencil mask
  1430. * @returns a number defining the new stencil mask to use
  1431. */
  1432. public getStencilMask(): number {
  1433. return this._stencilState.stencilMask;
  1434. }
  1435. /**
  1436. * Sets the current stencil mask
  1437. * @param mask defines the new stencil mask to use
  1438. */
  1439. public setStencilMask(mask: number): void {
  1440. this._stencilState.stencilMask = mask;
  1441. }
  1442. /**
  1443. * Gets the current stencil function
  1444. * @returns a number defining the stencil function to use
  1445. */
  1446. public getStencilFunction(): number {
  1447. return this._stencilState.stencilFunc;
  1448. }
  1449. /**
  1450. * Gets the current stencil reference value
  1451. * @returns a number defining the stencil reference value to use
  1452. */
  1453. public getStencilFunctionReference(): number {
  1454. return this._stencilState.stencilFuncRef;
  1455. }
  1456. /**
  1457. * Gets the current stencil mask
  1458. * @returns a number defining the stencil mask to use
  1459. */
  1460. public getStencilFunctionMask(): number {
  1461. return this._stencilState.stencilFuncMask;
  1462. }
  1463. /**
  1464. * Sets the current stencil function
  1465. * @param stencilFunc defines the new stencil function to use
  1466. */
  1467. public setStencilFunction(stencilFunc: number) {
  1468. this._stencilState.stencilFunc = stencilFunc;
  1469. }
  1470. /**
  1471. * Sets the current stencil reference
  1472. * @param reference defines the new stencil reference to use
  1473. */
  1474. public setStencilFunctionReference(reference: number) {
  1475. this._stencilState.stencilFuncRef = reference;
  1476. }
  1477. /**
  1478. * Sets the current stencil mask
  1479. * @param mask defines the new stencil mask to use
  1480. */
  1481. public setStencilFunctionMask(mask: number) {
  1482. this._stencilState.stencilFuncMask = mask;
  1483. }
  1484. /**
  1485. * Gets the current stencil operation when stencil fails
  1486. * @returns a number defining stencil operation to use when stencil fails
  1487. */
  1488. public getStencilOperationFail(): number {
  1489. return this._stencilState.stencilOpStencilFail;
  1490. }
  1491. /**
  1492. * Gets the current stencil operation when depth fails
  1493. * @returns a number defining stencil operation to use when depth fails
  1494. */
  1495. public getStencilOperationDepthFail(): number {
  1496. return this._stencilState.stencilOpDepthFail;
  1497. }
  1498. /**
  1499. * Gets the current stencil operation when stencil passes
  1500. * @returns a number defining stencil operation to use when stencil passes
  1501. */
  1502. public getStencilOperationPass(): number {
  1503. return this._stencilState.stencilOpStencilDepthPass;
  1504. }
  1505. /**
  1506. * Sets the stencil operation to use when stencil fails
  1507. * @param operation defines the stencil operation to use when stencil fails
  1508. */
  1509. public setStencilOperationFail(operation: number): void {
  1510. this._stencilState.stencilOpStencilFail = operation;
  1511. }
  1512. /**
  1513. * Sets the stencil operation to use when depth fails
  1514. * @param operation defines the stencil operation to use when depth fails
  1515. */
  1516. public setStencilOperationDepthFail(operation: number): void {
  1517. this._stencilState.stencilOpDepthFail = operation;
  1518. }
  1519. /**
  1520. * Sets the stencil operation to use when stencil passes
  1521. * @param operation defines the stencil operation to use when stencil passes
  1522. */
  1523. public setStencilOperationPass(operation: number): void {
  1524. this._stencilState.stencilOpStencilDepthPass = operation;
  1525. }
  1526. /**
  1527. * Sets a boolean indicating if the dithering state is enabled or disabled
  1528. * @param value defines the dithering state
  1529. */
  1530. public setDitheringState(value: boolean): void {
  1531. if (value) {
  1532. this._gl.enable(this._gl.DITHER);
  1533. } else {
  1534. this._gl.disable(this._gl.DITHER);
  1535. }
  1536. }
  1537. /**
  1538. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1539. * @param value defines the rasterizer state
  1540. */
  1541. public setRasterizerState(value: boolean): void {
  1542. if (value) {
  1543. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1544. } else {
  1545. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1546. }
  1547. }
  1548. /**
  1549. * stop executing a render loop function and remove it from the execution array
  1550. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1551. */
  1552. public stopRenderLoop(renderFunction?: () => void): void {
  1553. if (!renderFunction) {
  1554. this._activeRenderLoops = [];
  1555. return;
  1556. }
  1557. var index = this._activeRenderLoops.indexOf(renderFunction);
  1558. if (index >= 0) {
  1559. this._activeRenderLoops.splice(index, 1);
  1560. }
  1561. }
  1562. /** @hidden */
  1563. public _renderLoop(): void {
  1564. if (!this._contextWasLost) {
  1565. var shouldRender = true;
  1566. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1567. shouldRender = false;
  1568. }
  1569. if (shouldRender) {
  1570. // Start new frame
  1571. this.beginFrame();
  1572. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1573. var renderFunction = this._activeRenderLoops[index];
  1574. renderFunction();
  1575. }
  1576. // Present
  1577. this.endFrame();
  1578. }
  1579. }
  1580. if (this._activeRenderLoops.length > 0) {
  1581. // Register new frame
  1582. var requester = null;
  1583. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1584. requester = this._vrDisplay;
  1585. this._frameHandler = this._queueNewFrame(this._bindedRenderFunction, requester);
  1586. } else {
  1587. this._renderingQueueLaunched = false;
  1588. }
  1589. }
  1590. /**
  1591. * Can be used to override the current requestAnimationFrame requester.
  1592. * @hidden
  1593. */
  1594. protected _queueNewFrame(bindedRenderFunction: any, requester: any): number {
  1595. return Tools.QueueNewFrame(bindedRenderFunction, requester);
  1596. }
  1597. /**
  1598. * Register and execute a render loop. The engine can have more than one render function
  1599. * @param renderFunction defines the function to continuously execute
  1600. */
  1601. public runRenderLoop(renderFunction: () => void): void {
  1602. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1603. return;
  1604. }
  1605. this._activeRenderLoops.push(renderFunction);
  1606. if (!this._renderingQueueLaunched) {
  1607. this._renderingQueueLaunched = true;
  1608. this._bindedRenderFunction = this._renderLoop.bind(this);
  1609. this._frameHandler = this._queueNewFrame(this._bindedRenderFunction, undefined);
  1610. }
  1611. }
  1612. /**
  1613. * Toggle full screen mode
  1614. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1615. * @param options defines an option object to be sent to the requestFullscreen function
  1616. */
  1617. public switchFullscreen(requestPointerLock: boolean): void {
  1618. if (this.isFullscreen) {
  1619. Tools.ExitFullscreen();
  1620. } else {
  1621. this._pointerLockRequested = requestPointerLock;
  1622. if (this._renderingCanvas) {
  1623. Tools.RequestFullscreen(this._renderingCanvas);
  1624. }
  1625. }
  1626. }
  1627. /**
  1628. * Clear the current render buffer or the current render target (if any is set up)
  1629. * @param color defines the color to use
  1630. * @param backBuffer defines if the back buffer must be cleared
  1631. * @param depth defines if the depth buffer must be cleared
  1632. * @param stencil defines if the stencil buffer must be cleared
  1633. */
  1634. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1635. var mode = 0;
  1636. if (backBuffer && color) {
  1637. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1638. mode |= this._gl.COLOR_BUFFER_BIT;
  1639. }
  1640. if (depth) {
  1641. this._gl.clearDepth(1.0);
  1642. mode |= this._gl.DEPTH_BUFFER_BIT;
  1643. }
  1644. if (stencil) {
  1645. this._gl.clearStencil(0);
  1646. mode |= this._gl.STENCIL_BUFFER_BIT;
  1647. }
  1648. this._gl.clear(mode);
  1649. }
  1650. /**
  1651. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1652. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1653. * @param y defines the y-coordinate of the corner of the clear rectangle
  1654. * @param width defines the width of the clear rectangle
  1655. * @param height defines the height of the clear rectangle
  1656. * @param clearColor defines the clear color
  1657. */
  1658. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1659. let gl = this._gl;
  1660. // Save state
  1661. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1662. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1663. // Change state
  1664. gl.enable(gl.SCISSOR_TEST);
  1665. gl.scissor(x, y, width, height);
  1666. // Clear
  1667. this.clear(clearColor, true, true, true);
  1668. // Restore state
  1669. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1670. if (curScissor === true) {
  1671. gl.enable(gl.SCISSOR_TEST);
  1672. } else {
  1673. gl.disable(gl.SCISSOR_TEST);
  1674. }
  1675. }
  1676. private _viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  1677. /** @hidden */
  1678. public _viewport(x: number, y: number, width: number, height: number): void {
  1679. if (x !== this._viewportCached.x ||
  1680. y !== this._viewportCached.y ||
  1681. width !== this._viewportCached.z ||
  1682. height !== this._viewportCached.w)
  1683. {
  1684. this._viewportCached.x = x;
  1685. this._viewportCached.y = y;
  1686. this._viewportCached.z = width;
  1687. this._viewportCached.w = height;
  1688. this._gl.viewport(x, y, width, height);
  1689. }
  1690. }
  1691. /**
  1692. * Set the WebGL's viewport
  1693. * @param viewport defines the viewport element to be used
  1694. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1695. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1696. */
  1697. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1698. var width = requiredWidth || this.getRenderWidth();
  1699. var height = requiredHeight || this.getRenderHeight();
  1700. var x = viewport.x || 0;
  1701. var y = viewport.y || 0;
  1702. this._cachedViewport = viewport;
  1703. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1704. }
  1705. /**
  1706. * Directly set the WebGL Viewport
  1707. * @param x defines the x coordinate of the viewport (in screen space)
  1708. * @param y defines the y coordinate of the viewport (in screen space)
  1709. * @param width defines the width of the viewport (in screen space)
  1710. * @param height defines the height of the viewport (in screen space)
  1711. * @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
  1712. */
  1713. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1714. let currentViewport = this._cachedViewport;
  1715. this._cachedViewport = null;
  1716. this._viewport(x, y, width, height);
  1717. return currentViewport;
  1718. }
  1719. /**
  1720. * Begin a new frame
  1721. */
  1722. public beginFrame(): void {
  1723. this.onBeginFrameObservable.notifyObservers(this);
  1724. this._measureFps();
  1725. }
  1726. /**
  1727. * Enf the current frame
  1728. */
  1729. public endFrame(): void {
  1730. // Force a flush in case we are using a bad OS.
  1731. if (this._badOS) {
  1732. this.flushFramebuffer();
  1733. }
  1734. // Submit frame to the vr device, if enabled
  1735. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1736. // TODO: We should only submit the frame if we read frameData successfully.
  1737. this._vrDisplay.submitFrame();
  1738. }
  1739. this.onEndFrameObservable.notifyObservers(this);
  1740. }
  1741. /**
  1742. * Resize the view according to the canvas' size
  1743. */
  1744. public resize(): void {
  1745. // We're not resizing the size of the canvas while in VR mode & presenting
  1746. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1747. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1748. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1749. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1750. }
  1751. }
  1752. /**
  1753. * Force a specific size of the canvas
  1754. * @param width defines the new canvas' width
  1755. * @param height defines the new canvas' height
  1756. */
  1757. public setSize(width: number, height: number): void {
  1758. if (!this._renderingCanvas) {
  1759. return;
  1760. }
  1761. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1762. return;
  1763. }
  1764. this._renderingCanvas.width = width;
  1765. this._renderingCanvas.height = height;
  1766. for (var index = 0; index < this.scenes.length; index++) {
  1767. var scene = this.scenes[index];
  1768. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1769. var cam = scene.cameras[camIndex];
  1770. cam._currentRenderId = 0;
  1771. }
  1772. }
  1773. if (this.onResizeObservable.hasObservers) {
  1774. this.onResizeObservable.notifyObservers(this);
  1775. }
  1776. }
  1777. // WebVR functions
  1778. /**
  1779. * Gets a boolean indicating if a webVR device was detected
  1780. * @returns true if a webVR device was detected
  1781. */
  1782. public isVRDevicePresent(): boolean {
  1783. return !!this._vrDisplay;
  1784. }
  1785. /**
  1786. * Gets the current webVR device
  1787. * @returns the current webVR device (or null)
  1788. */
  1789. public getVRDevice(): any {
  1790. return this._vrDisplay;
  1791. }
  1792. /**
  1793. * Initializes a webVR display and starts listening to display change events
  1794. * The onVRDisplayChangedObservable will be notified upon these changes
  1795. * @returns The onVRDisplayChangedObservable
  1796. */
  1797. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1798. this.initWebVRAsync();
  1799. return this.onVRDisplayChangedObservable;
  1800. }
  1801. /**
  1802. * Initializes a webVR display and starts listening to display change events
  1803. * The onVRDisplayChangedObservable will be notified upon these changes
  1804. * @returns A promise containing a VRDisplay and if vr is supported
  1805. */
  1806. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1807. var notifyObservers = () => {
  1808. var eventArgs = {
  1809. vrDisplay: this._vrDisplay,
  1810. vrSupported: this._vrSupported
  1811. };
  1812. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1813. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1814. }
  1815. if (!this._onVrDisplayConnect) {
  1816. this._onVrDisplayConnect = (event) => {
  1817. this._vrDisplay = event.display;
  1818. notifyObservers();
  1819. };
  1820. this._onVrDisplayDisconnect = () => {
  1821. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1822. this._vrDisplay = undefined;
  1823. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1824. notifyObservers();
  1825. };
  1826. this._onVrDisplayPresentChange = () => {
  1827. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1828. }
  1829. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1830. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1831. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1832. }
  1833. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1834. this._webVRInitPromise.then(notifyObservers);
  1835. return this._webVRInitPromise;
  1836. }
  1837. /**
  1838. * Call this function to switch to webVR mode
  1839. * Will do nothing if webVR is not supported or if there is no webVR device
  1840. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1841. */
  1842. public enableVR() {
  1843. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1844. var onResolved = () => {
  1845. this.onVRRequestPresentComplete.notifyObservers(true);
  1846. this._onVRFullScreenTriggered();
  1847. };
  1848. var onRejected = () => {
  1849. this.onVRRequestPresentComplete.notifyObservers(false);
  1850. };
  1851. this.onVRRequestPresentStart.notifyObservers(this);
  1852. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1853. }
  1854. }
  1855. /**
  1856. * Call this function to leave webVR mode
  1857. * Will do nothing if webVR is not supported or if there is no webVR device
  1858. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1859. */
  1860. public disableVR() {
  1861. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1862. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1863. }
  1864. }
  1865. private _onVRFullScreenTriggered = () => {
  1866. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1867. //get the old size before we change
  1868. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1869. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1870. //get the width and height, change the render size
  1871. var leftEye = this._vrDisplay.getEyeParameters('left');
  1872. this.setHardwareScalingLevel(1);
  1873. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1874. } else {
  1875. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1876. this.setSize(this._oldSize.width, this._oldSize.height);
  1877. }
  1878. }
  1879. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  1880. return new Promise((res, rej)=>{
  1881. if (navigator.getVRDisplays) {
  1882. navigator.getVRDisplays().then((devices: Array<any>)=>{
  1883. this._vrSupported = true;
  1884. // note that devices may actually be an empty array. This is fine;
  1885. // we expect this._vrDisplay to be undefined in this case.
  1886. this._vrDisplay = devices[0];
  1887. res({
  1888. vrDisplay: this._vrDisplay,
  1889. vrSupported: this._vrSupported
  1890. });
  1891. });
  1892. } else {
  1893. this._vrDisplay = undefined;
  1894. this._vrSupported = false;
  1895. res({
  1896. vrDisplay: this._vrDisplay,
  1897. vrSupported: this._vrSupported
  1898. });
  1899. }
  1900. });
  1901. }
  1902. /**
  1903. * Binds the frame buffer to the specified texture.
  1904. * @param texture The texture to render to or null for the default canvas
  1905. * @param faceIndex The face of the texture to render to in case of cube texture
  1906. * @param requiredWidth The width of the target to render to
  1907. * @param requiredHeight The height of the target to render to
  1908. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1909. * @param depthStencilTexture The depth stencil texture to use to render
  1910. * @param lodLevel defines le lod level to bind to the frame buffer
  1911. */
  1912. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  1913. if (this._currentRenderTarget) {
  1914. this.unBindFramebuffer(this._currentRenderTarget);
  1915. }
  1916. this._currentRenderTarget = texture;
  1917. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1918. var gl = this._gl;
  1919. if (texture.isCube) {
  1920. if (faceIndex === undefined) {
  1921. faceIndex = 0;
  1922. }
  1923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1924. if (depthStencilTexture) {
  1925. if (depthStencilTexture._generateStencilBuffer) {
  1926. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1927. }
  1928. else {
  1929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1930. }
  1931. }
  1932. }
  1933. if (this._cachedViewport && !forceFullscreenViewport) {
  1934. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1935. } else {
  1936. if (!requiredWidth) {
  1937. requiredWidth = texture.width;
  1938. if (lodLevel) {
  1939. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1940. }
  1941. }
  1942. if (!requiredHeight) {
  1943. requiredHeight = texture.height;
  1944. if (lodLevel) {
  1945. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1946. }
  1947. }
  1948. this._viewport(0, 0, requiredWidth, requiredHeight);
  1949. }
  1950. this.wipeCaches();
  1951. }
  1952. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1953. if (this._currentFramebuffer !== framebuffer) {
  1954. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1955. this._currentFramebuffer = framebuffer;
  1956. }
  1957. }
  1958. /**
  1959. * Unbind the current render target texture from the webGL context
  1960. * @param texture defines the render target texture to unbind
  1961. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1962. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1963. */
  1964. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1965. this._currentRenderTarget = null;
  1966. // If MSAA, we need to bitblt back to main texture
  1967. var gl = this._gl;
  1968. if (texture._MSAAFramebuffer) {
  1969. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1970. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1971. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1972. 0, 0, texture.width, texture.height,
  1973. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1974. }
  1975. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1976. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1977. gl.generateMipmap(gl.TEXTURE_2D);
  1978. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1979. }
  1980. if (onBeforeUnbind) {
  1981. if (texture._MSAAFramebuffer) {
  1982. // Bind the correct framebuffer
  1983. this.bindUnboundFramebuffer(texture._framebuffer);
  1984. }
  1985. onBeforeUnbind();
  1986. }
  1987. this.bindUnboundFramebuffer(null);
  1988. }
  1989. /**
  1990. * Unbind a list of render target textures from the webGL context
  1991. * This is used only when drawBuffer extension or webGL2 are active
  1992. * @param textures defines the render target textures to unbind
  1993. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1994. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1995. */
  1996. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1997. this._currentRenderTarget = null;
  1998. // If MSAA, we need to bitblt back to main texture
  1999. var gl = this._gl;
  2000. if (textures[0]._MSAAFramebuffer) {
  2001. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  2002. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  2003. var attachments = textures[0]._attachments;
  2004. if (!attachments) {
  2005. attachments = new Array(textures.length);
  2006. textures[0]._attachments = attachments;
  2007. }
  2008. for (var i = 0; i < textures.length; i++) {
  2009. var texture = textures[i];
  2010. for (var j = 0; j < attachments.length; j++) {
  2011. attachments[j] = gl.NONE;
  2012. }
  2013. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2014. gl.readBuffer(attachments[i]);
  2015. gl.drawBuffers(attachments);
  2016. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2017. 0, 0, texture.width, texture.height,
  2018. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2019. }
  2020. for (var i = 0; i < attachments.length; i++) {
  2021. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2022. }
  2023. gl.drawBuffers(attachments);
  2024. }
  2025. for (var i = 0; i < textures.length; i++) {
  2026. var texture = textures[i];
  2027. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2028. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2029. gl.generateMipmap(gl.TEXTURE_2D);
  2030. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2031. }
  2032. }
  2033. if (onBeforeUnbind) {
  2034. if (textures[0]._MSAAFramebuffer) {
  2035. // Bind the correct framebuffer
  2036. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  2037. }
  2038. onBeforeUnbind();
  2039. }
  2040. this.bindUnboundFramebuffer(null);
  2041. }
  2042. /**
  2043. * Force the mipmap generation for the given render target texture
  2044. * @param texture defines the render target texture to use
  2045. */
  2046. public generateMipMapsForCubemap(texture: InternalTexture) {
  2047. if (texture.generateMipMaps) {
  2048. var gl = this._gl;
  2049. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2050. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2051. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2052. }
  2053. }
  2054. /**
  2055. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2056. */
  2057. public flushFramebuffer(): void {
  2058. this._gl.flush();
  2059. }
  2060. /**
  2061. * Unbind the current render target and bind the default framebuffer
  2062. */
  2063. public restoreDefaultFramebuffer(): void {
  2064. if (this._currentRenderTarget) {
  2065. this.unBindFramebuffer(this._currentRenderTarget);
  2066. } else {
  2067. this.bindUnboundFramebuffer(null);
  2068. }
  2069. if (this._cachedViewport) {
  2070. this.setViewport(this._cachedViewport);
  2071. }
  2072. this.wipeCaches();
  2073. }
  2074. // UBOs
  2075. /**
  2076. * Create an uniform buffer
  2077. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2078. * @param elements defines the content of the uniform buffer
  2079. * @returns the webGL uniform buffer
  2080. */
  2081. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2082. var ubo = this._gl.createBuffer();
  2083. if (!ubo) {
  2084. throw new Error("Unable to create uniform buffer");
  2085. }
  2086. this.bindUniformBuffer(ubo);
  2087. if (elements instanceof Float32Array) {
  2088. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2089. } else {
  2090. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2091. }
  2092. this.bindUniformBuffer(null);
  2093. ubo.references = 1;
  2094. return ubo;
  2095. }
  2096. /**
  2097. * Create a dynamic uniform buffer
  2098. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2099. * @param elements defines the content of the uniform buffer
  2100. * @returns the webGL uniform buffer
  2101. */
  2102. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2103. var ubo = this._gl.createBuffer();
  2104. if (!ubo) {
  2105. throw new Error("Unable to create dynamic uniform buffer");
  2106. }
  2107. this.bindUniformBuffer(ubo);
  2108. if (elements instanceof Float32Array) {
  2109. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2110. } else {
  2111. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2112. }
  2113. this.bindUniformBuffer(null);
  2114. ubo.references = 1;
  2115. return ubo;
  2116. }
  2117. /**
  2118. * Update an existing uniform buffer
  2119. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2120. * @param uniformBuffer defines the target uniform buffer
  2121. * @param elements defines the content to update
  2122. * @param offset defines the offset in the uniform buffer where update should start
  2123. * @param count defines the size of the data to update
  2124. */
  2125. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2126. this.bindUniformBuffer(uniformBuffer);
  2127. if (offset === undefined) {
  2128. offset = 0;
  2129. }
  2130. if (count === undefined) {
  2131. if (elements instanceof Float32Array) {
  2132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2133. } else {
  2134. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2135. }
  2136. } else {
  2137. if (elements instanceof Float32Array) {
  2138. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2139. } else {
  2140. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2141. }
  2142. }
  2143. this.bindUniformBuffer(null);
  2144. }
  2145. // VBOs
  2146. private _resetVertexBufferBinding(): void {
  2147. this.bindArrayBuffer(null);
  2148. this._cachedVertexBuffers = null;
  2149. }
  2150. /**
  2151. * Creates a vertex buffer
  2152. * @param data the data for the vertex buffer
  2153. * @returns the new WebGL static buffer
  2154. */
  2155. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2156. var vbo = this._gl.createBuffer();
  2157. if (!vbo) {
  2158. throw new Error("Unable to create vertex buffer");
  2159. }
  2160. this.bindArrayBuffer(vbo);
  2161. if (data instanceof Array) {
  2162. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2163. } else {
  2164. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2165. }
  2166. this._resetVertexBufferBinding();
  2167. vbo.references = 1;
  2168. return vbo;
  2169. }
  2170. /**
  2171. * Creates a dynamic vertex buffer
  2172. * @param data the data for the dynamic vertex buffer
  2173. * @returns the new WebGL dynamic buffer
  2174. */
  2175. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2176. var vbo = this._gl.createBuffer();
  2177. if (!vbo) {
  2178. throw new Error("Unable to create dynamic vertex buffer");
  2179. }
  2180. this.bindArrayBuffer(vbo);
  2181. if (data instanceof Array) {
  2182. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2183. } else {
  2184. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2185. }
  2186. this._resetVertexBufferBinding();
  2187. vbo.references = 1;
  2188. return vbo;
  2189. }
  2190. /**
  2191. * Update a dynamic index buffer
  2192. * @param indexBuffer defines the target index buffer
  2193. * @param indices defines the data to update
  2194. * @param offset defines the offset in the target index buffer where update should start
  2195. */
  2196. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2197. // Force cache update
  2198. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2199. this.bindIndexBuffer(indexBuffer);
  2200. var arrayBuffer;
  2201. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2202. arrayBuffer = indices;
  2203. } else {
  2204. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2205. }
  2206. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2207. this._resetIndexBufferBinding();
  2208. }
  2209. /**
  2210. * Updates a dynamic vertex buffer.
  2211. * @param vertexBuffer the vertex buffer to update
  2212. * @param data the data used to update the vertex buffer
  2213. * @param byteOffset the byte offset of the data
  2214. * @param byteLength the byte length of the data
  2215. */
  2216. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2217. this.bindArrayBuffer(vertexBuffer);
  2218. if (byteOffset === undefined) {
  2219. byteOffset = 0;
  2220. }
  2221. if (byteLength === undefined) {
  2222. if (data instanceof Array) {
  2223. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2224. } else {
  2225. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2226. }
  2227. } else {
  2228. if (data instanceof Array) {
  2229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2230. } else {
  2231. if (data instanceof ArrayBuffer) {
  2232. data = new Uint8Array(data, byteOffset, byteLength);
  2233. } else {
  2234. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2235. }
  2236. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2237. }
  2238. }
  2239. this._resetVertexBufferBinding();
  2240. }
  2241. private _resetIndexBufferBinding(): void {
  2242. this.bindIndexBuffer(null);
  2243. this._cachedIndexBuffer = null;
  2244. }
  2245. /**
  2246. * Creates a new index buffer
  2247. * @param indices defines the content of the index buffer
  2248. * @param updatable defines if the index buffer must be updatable
  2249. * @returns a new webGL buffer
  2250. */
  2251. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2252. var vbo = this._gl.createBuffer();
  2253. if (!vbo) {
  2254. throw new Error("Unable to create index buffer");
  2255. }
  2256. this.bindIndexBuffer(vbo);
  2257. // Check for 32 bits indices
  2258. var arrayBuffer;
  2259. var need32Bits = false;
  2260. if (indices instanceof Uint16Array) {
  2261. arrayBuffer = indices;
  2262. } else {
  2263. //check 32 bit support
  2264. if (this._caps.uintIndices) {
  2265. if (indices instanceof Uint32Array) {
  2266. arrayBuffer = indices;
  2267. need32Bits = true;
  2268. } else {
  2269. //number[] or Int32Array, check if 32 bit is necessary
  2270. for (var index = 0; index < indices.length; index++) {
  2271. if (indices[index] > 65535) {
  2272. need32Bits = true;
  2273. break;
  2274. }
  2275. }
  2276. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2277. }
  2278. } else {
  2279. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2280. arrayBuffer = new Uint16Array(indices);
  2281. }
  2282. }
  2283. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2284. this._resetIndexBufferBinding();
  2285. vbo.references = 1;
  2286. vbo.is32Bits = need32Bits;
  2287. return vbo;
  2288. }
  2289. /**
  2290. * Bind a webGL buffer to the webGL context
  2291. * @param buffer defines the buffer to bind
  2292. */
  2293. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2294. if (!this._vaoRecordInProgress) {
  2295. this._unbindVertexArrayObject();
  2296. }
  2297. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2298. }
  2299. /**
  2300. * Bind an uniform buffer to the current webGL context
  2301. * @param buffer defines the buffer to bind
  2302. */
  2303. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2304. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2305. }
  2306. /**
  2307. * Bind a buffer to the current webGL context at a given location
  2308. * @param buffer defines the buffer to bind
  2309. * @param location defines the index where to bind the buffer
  2310. */
  2311. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2312. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2313. }
  2314. /**
  2315. * Bind a specific block at a given index in a specific shader program
  2316. * @param shaderProgram defines the shader program
  2317. * @param blockName defines the block name
  2318. * @param index defines the index where to bind the block
  2319. */
  2320. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2321. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2322. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2323. };
  2324. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2325. if (!this._vaoRecordInProgress) {
  2326. this._unbindVertexArrayObject();
  2327. }
  2328. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2329. }
  2330. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2331. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2332. this._gl.bindBuffer(target, buffer);
  2333. this._currentBoundBuffer[target] = buffer;
  2334. }
  2335. }
  2336. /**
  2337. * update the bound buffer with the given data
  2338. * @param data defines the data to update
  2339. */
  2340. public updateArrayBuffer(data: Float32Array): void {
  2341. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2342. }
  2343. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2344. var pointer = this._currentBufferPointers[indx];
  2345. var changed = false;
  2346. if (!pointer.active) {
  2347. changed = true;
  2348. pointer.active = true;
  2349. pointer.index = indx;
  2350. pointer.size = size;
  2351. pointer.type = type;
  2352. pointer.normalized = normalized;
  2353. pointer.stride = stride;
  2354. pointer.offset = offset;
  2355. pointer.buffer = buffer;
  2356. } else {
  2357. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2358. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2359. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2360. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2361. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2362. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2363. }
  2364. if (changed || this._vaoRecordInProgress) {
  2365. this.bindArrayBuffer(buffer);
  2366. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2367. }
  2368. }
  2369. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2370. if (indexBuffer == null) {
  2371. return;
  2372. }
  2373. if (this._cachedIndexBuffer !== indexBuffer) {
  2374. this._cachedIndexBuffer = indexBuffer;
  2375. this.bindIndexBuffer(indexBuffer);
  2376. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2377. }
  2378. }
  2379. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2380. var attributes = effect.getAttributesNames();
  2381. if (!this._vaoRecordInProgress) {
  2382. this._unbindVertexArrayObject();
  2383. }
  2384. this.unbindAllAttributes();
  2385. for (var index = 0; index < attributes.length; index++) {
  2386. var order = effect.getAttributeLocation(index);
  2387. if (order >= 0) {
  2388. var vertexBuffer = vertexBuffers[attributes[index]];
  2389. if (!vertexBuffer) {
  2390. continue;
  2391. }
  2392. this._gl.enableVertexAttribArray(order);
  2393. if (!this._vaoRecordInProgress) {
  2394. this._vertexAttribArraysEnabled[order] = true;
  2395. }
  2396. var buffer = vertexBuffer.getBuffer();
  2397. if (buffer) {
  2398. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2399. if (vertexBuffer.getIsInstanced()) {
  2400. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2401. if (!this._vaoRecordInProgress) {
  2402. this._currentInstanceLocations.push(order);
  2403. this._currentInstanceBuffers.push(buffer);
  2404. }
  2405. }
  2406. }
  2407. }
  2408. }
  2409. }
  2410. /**
  2411. * Records a vertex array object
  2412. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2413. * @param vertexBuffers defines the list of vertex buffers to store
  2414. * @param indexBuffer defines the index buffer to store
  2415. * @param effect defines the effect to store
  2416. * @returns the new vertex array object
  2417. */
  2418. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2419. var vao = this._gl.createVertexArray();
  2420. this._vaoRecordInProgress = true;
  2421. this._gl.bindVertexArray(vao);
  2422. this._mustWipeVertexAttributes = true;
  2423. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2424. this.bindIndexBuffer(indexBuffer);
  2425. this._vaoRecordInProgress = false;
  2426. this._gl.bindVertexArray(null);
  2427. return vao;
  2428. }
  2429. /**
  2430. * Bind a specific vertex array object
  2431. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2432. * @param vertexArrayObject defines the vertex array object to bind
  2433. * @param indexBuffer defines the index buffer to bind
  2434. */
  2435. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2436. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2437. this._cachedVertexArrayObject = vertexArrayObject;
  2438. this._gl.bindVertexArray(vertexArrayObject);
  2439. this._cachedVertexBuffers = null;
  2440. this._cachedIndexBuffer = null;
  2441. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2442. this._mustWipeVertexAttributes = true;
  2443. }
  2444. }
  2445. /**
  2446. * Bind webGl buffers directly to the webGL context
  2447. * @param vertexBuffer defines the vertex buffer to bind
  2448. * @param indexBuffer defines the index buffer to bind
  2449. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2450. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2451. * @param effect defines the effect associated with the vertex buffer
  2452. */
  2453. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2454. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2455. this._cachedVertexBuffers = vertexBuffer;
  2456. this._cachedEffectForVertexBuffers = effect;
  2457. let attributesCount = effect.getAttributesCount();
  2458. this._unbindVertexArrayObject();
  2459. this.unbindAllAttributes();
  2460. var offset = 0;
  2461. for (var index = 0; index < attributesCount; index++) {
  2462. if (index < vertexDeclaration.length) {
  2463. var order = effect.getAttributeLocation(index);
  2464. if (order >= 0) {
  2465. this._gl.enableVertexAttribArray(order);
  2466. this._vertexAttribArraysEnabled[order] = true;
  2467. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2468. }
  2469. offset += vertexDeclaration[index] * 4;
  2470. }
  2471. }
  2472. }
  2473. this._bindIndexBufferWithCache(indexBuffer);
  2474. }
  2475. private _unbindVertexArrayObject(): void {
  2476. if (!this._cachedVertexArrayObject) {
  2477. return;
  2478. }
  2479. this._cachedVertexArrayObject = null;
  2480. this._gl.bindVertexArray(null);
  2481. }
  2482. /**
  2483. * Bind a list of vertex buffers to the webGL context
  2484. * @param vertexBuffers defines the list of vertex buffers to bind
  2485. * @param indexBuffer defines the index buffer to bind
  2486. * @param effect defines the effect associated with the vertex buffers
  2487. */
  2488. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2489. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2490. this._cachedVertexBuffers = vertexBuffers;
  2491. this._cachedEffectForVertexBuffers = effect;
  2492. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2493. }
  2494. this._bindIndexBufferWithCache(indexBuffer);
  2495. }
  2496. /**
  2497. * Unbind all instance attributes
  2498. */
  2499. public unbindInstanceAttributes() {
  2500. var boundBuffer;
  2501. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2502. var instancesBuffer = this._currentInstanceBuffers[i];
  2503. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2504. boundBuffer = instancesBuffer;
  2505. this.bindArrayBuffer(instancesBuffer);
  2506. }
  2507. var offsetLocation = this._currentInstanceLocations[i];
  2508. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2509. }
  2510. this._currentInstanceBuffers.length = 0;
  2511. this._currentInstanceLocations.length = 0;
  2512. }
  2513. /**
  2514. * Release and free the memory of a vertex array object
  2515. * @param vao defines the vertex array object to delete
  2516. */
  2517. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2518. this._gl.deleteVertexArray(vao);
  2519. }
  2520. /** @hidden */
  2521. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2522. buffer.references--;
  2523. if (buffer.references === 0) {
  2524. this._gl.deleteBuffer(buffer);
  2525. return true;
  2526. }
  2527. return false;
  2528. }
  2529. protected _deleteBuffer(buffer: WebGLBuffer): void {
  2530. this._gl.deleteBuffer(buffer);
  2531. }
  2532. /**
  2533. * Creates a webGL buffer to use with instanciation
  2534. * @param capacity defines the size of the buffer
  2535. * @returns the webGL buffer
  2536. */
  2537. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2538. var buffer = this._gl.createBuffer();
  2539. if (!buffer) {
  2540. throw new Error("Unable to create instance buffer");
  2541. }
  2542. buffer.capacity = capacity;
  2543. this.bindArrayBuffer(buffer);
  2544. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2545. return buffer;
  2546. }
  2547. /**
  2548. * Delete a webGL buffer used with instanciation
  2549. * @param buffer defines the webGL buffer to delete
  2550. */
  2551. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2552. this._gl.deleteBuffer(buffer);
  2553. }
  2554. /**
  2555. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2556. * @param instancesBuffer defines the webGL buffer to update and bind
  2557. * @param data defines the data to store in the buffer
  2558. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2559. */
  2560. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2561. this.bindArrayBuffer(instancesBuffer);
  2562. if (data) {
  2563. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2564. }
  2565. if ((<any>offsetLocations[0]).index !== undefined) {
  2566. let stride = 0;
  2567. for (let i = 0; i < offsetLocations.length; i++) {
  2568. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2569. stride += ai.attributeSize * 4;
  2570. }
  2571. for (let i = 0; i < offsetLocations.length; i++) {
  2572. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2573. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2574. this._gl.enableVertexAttribArray(ai.index);
  2575. this._vertexAttribArraysEnabled[ai.index] = true;
  2576. }
  2577. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2578. this._gl.vertexAttribDivisor(ai.index, 1);
  2579. this._currentInstanceLocations.push(ai.index);
  2580. this._currentInstanceBuffers.push(instancesBuffer);
  2581. }
  2582. } else {
  2583. for (let index = 0; index < 4; index++) {
  2584. let offsetLocation = <number>offsetLocations[index];
  2585. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2586. this._gl.enableVertexAttribArray(offsetLocation);
  2587. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2588. }
  2589. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2590. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2591. this._currentInstanceLocations.push(offsetLocation);
  2592. this._currentInstanceBuffers.push(instancesBuffer);
  2593. }
  2594. }
  2595. }
  2596. /**
  2597. * Apply all cached states (depth, culling, stencil and alpha)
  2598. */
  2599. public applyStates() {
  2600. this._depthCullingState.apply(this._gl);
  2601. this._stencilState.apply(this._gl);
  2602. this._alphaState.apply(this._gl);
  2603. }
  2604. /**
  2605. * Send a draw order
  2606. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2607. * @param indexStart defines the starting index
  2608. * @param indexCount defines the number of index to draw
  2609. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2610. */
  2611. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2612. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2613. }
  2614. /**
  2615. * Draw a list of points
  2616. * @param verticesStart defines the index of first vertex to draw
  2617. * @param verticesCount defines the count of vertices to draw
  2618. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2619. */
  2620. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2621. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2622. }
  2623. /**
  2624. * Draw a list of unindexed primitives
  2625. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2626. * @param verticesStart defines the index of first vertex to draw
  2627. * @param verticesCount defines the count of vertices to draw
  2628. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2629. */
  2630. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2631. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2632. }
  2633. /**
  2634. * Draw a list of indexed primitives
  2635. * @param fillMode defines the primitive to use
  2636. * @param indexStart defines the starting index
  2637. * @param indexCount defines the number of index to draw
  2638. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2639. */
  2640. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2641. // Apply states
  2642. this.applyStates();
  2643. this._drawCalls.addCount(1, false);
  2644. // Render
  2645. const drawMode = this._drawMode(fillMode);
  2646. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2647. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2648. if (instancesCount) {
  2649. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2650. } else {
  2651. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2652. }
  2653. }
  2654. /**
  2655. * Draw a list of unindexed primitives
  2656. * @param fillMode defines the primitive to use
  2657. * @param verticesStart defines the index of first vertex to draw
  2658. * @param verticesCount defines the count of vertices to draw
  2659. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2660. */
  2661. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2662. // Apply states
  2663. this.applyStates();
  2664. this._drawCalls.addCount(1, false);
  2665. const drawMode = this._drawMode(fillMode);
  2666. if (instancesCount) {
  2667. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2668. } else {
  2669. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2670. }
  2671. }
  2672. private _drawMode(fillMode: number): number {
  2673. switch (fillMode) {
  2674. // Triangle views
  2675. case Material.TriangleFillMode:
  2676. return this._gl.TRIANGLES;
  2677. case Material.PointFillMode:
  2678. return this._gl.POINTS;
  2679. case Material.WireFrameFillMode:
  2680. return this._gl.LINES;
  2681. // Draw modes
  2682. case Material.PointListDrawMode:
  2683. return this._gl.POINTS
  2684. case Material.LineListDrawMode:
  2685. return this._gl.LINES;
  2686. case Material.LineLoopDrawMode:
  2687. return this._gl.LINE_LOOP
  2688. case Material.LineStripDrawMode:
  2689. return this._gl.LINE_STRIP
  2690. case Material.TriangleStripDrawMode:
  2691. return this._gl.TRIANGLE_STRIP
  2692. case Material.TriangleFanDrawMode:
  2693. return this._gl.TRIANGLE_FAN;
  2694. default:
  2695. return this._gl.TRIANGLES;
  2696. }
  2697. }
  2698. // Shaders
  2699. /** @hidden */
  2700. public _releaseEffect(effect: Effect): void {
  2701. if (this._compiledEffects[effect._key]) {
  2702. delete this._compiledEffects[effect._key];
  2703. this._deleteProgram(effect.getProgram());
  2704. }
  2705. }
  2706. /** @hidden */
  2707. public _deleteProgram(program: WebGLProgram): void {
  2708. if (program) {
  2709. program.__SPECTOR_rebuildProgram = null;
  2710. if (program.transformFeedback) {
  2711. this.deleteTransformFeedback(program.transformFeedback);
  2712. program.transformFeedback = null;
  2713. }
  2714. this._gl.deleteProgram(program);
  2715. }
  2716. }
  2717. /**
  2718. * Create a new effect (used to store vertex/fragment shaders)
  2719. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2720. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2721. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2722. * @param samplers defines an array of string used to represent textures
  2723. * @param defines defines the string containing the defines to use to compile the shaders
  2724. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2725. * @param onCompiled defines a function to call when the effect creation is successful
  2726. * @param onError defines a function to call when the effect creation has failed
  2727. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2728. * @returns the new Effect
  2729. */
  2730. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2731. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2732. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2733. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2734. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2735. if (this._compiledEffects[name]) {
  2736. var compiledEffect = <Effect>this._compiledEffects[name];
  2737. if (onCompiled && compiledEffect.isReady()) {
  2738. onCompiled(compiledEffect);
  2739. }
  2740. return compiledEffect;
  2741. }
  2742. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2743. effect._key = name;
  2744. this._compiledEffects[name] = effect;
  2745. return effect;
  2746. }
  2747. protected static _concatenateShader(source: string, defines: Nullable<string>, shaderVersion: string): string {
  2748. return shaderVersion + (defines ? defines + "\n" : "") + source;
  2749. }
  2750. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  2751. return this._compileRawShader(Engine._concatenateShader(source, defines, shaderVersion), type);
  2752. };
  2753. private _compileRawShader(source: string, type: string): WebGLShader {
  2754. var gl = this._gl;
  2755. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2756. gl.shaderSource(shader, source);
  2757. gl.compileShader(shader);
  2758. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2759. let log = gl.getShaderInfoLog(shader);
  2760. if (log) {
  2761. throw new Error(log);
  2762. }
  2763. }
  2764. if (!shader) {
  2765. throw new Error("Something went wrong while compile the shader.");
  2766. }
  2767. return shader;
  2768. };
  2769. /**
  2770. * Directly creates a webGL program
  2771. * @param vertexCode defines the vertex shader code to use
  2772. * @param fragmentCode defines the fragment shader code to use
  2773. * @param context defines the webGL context to use (if not set, the current one will be used)
  2774. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2775. * @returns the new webGL program
  2776. */
  2777. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2778. context = context || this._gl;
  2779. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  2780. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  2781. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2782. }
  2783. /**
  2784. * Creates a webGL program
  2785. * @param vertexCode defines the vertex shader code to use
  2786. * @param fragmentCode defines the fragment shader code to use
  2787. * @param defines defines the string containing the defines to use to compile the shaders
  2788. * @param context defines the webGL context to use (if not set, the current one will be used)
  2789. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2790. * @returns the new webGL program
  2791. */
  2792. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2793. context = context || this._gl;
  2794. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2795. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2796. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  2797. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  2798. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2799. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2800. return program;
  2801. }
  2802. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2803. var shaderProgram = context.createProgram();
  2804. if (!shaderProgram) {
  2805. throw new Error("Unable to create program");
  2806. }
  2807. context.attachShader(shaderProgram, vertexShader);
  2808. context.attachShader(shaderProgram, fragmentShader);
  2809. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2810. let transformFeedback = this.createTransformFeedback();
  2811. this.bindTransformFeedback(transformFeedback);
  2812. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2813. shaderProgram.transformFeedback = transformFeedback;
  2814. }
  2815. context.linkProgram(shaderProgram);
  2816. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2817. this.bindTransformFeedback(null);
  2818. }
  2819. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2820. if (!linked) {
  2821. var error = context.getProgramInfoLog(shaderProgram);
  2822. if (error) {
  2823. throw new Error(error);
  2824. }
  2825. }
  2826. if (this.validateShaderPrograms) {
  2827. context.validateProgram(shaderProgram);
  2828. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  2829. if(!validated) {
  2830. var error = context.getProgramInfoLog(shaderProgram);
  2831. if (error) {
  2832. throw new Error(error);
  2833. }
  2834. }
  2835. }
  2836. context.deleteShader(vertexShader);
  2837. context.deleteShader(fragmentShader);
  2838. return shaderProgram;
  2839. }
  2840. /**
  2841. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2842. * @param shaderProgram defines the webGL program to use
  2843. * @param uniformsNames defines the list of uniform names
  2844. * @returns an array of webGL uniform locations
  2845. */
  2846. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2847. var results = new Array<Nullable<WebGLUniformLocation>>();
  2848. for (var index = 0; index < uniformsNames.length; index++) {
  2849. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2850. }
  2851. return results;
  2852. }
  2853. /**
  2854. * Gets the list of active attributes for a given webGL program
  2855. * @param shaderProgram defines the webGL program to use
  2856. * @param attributesNames defines the list of attribute names to get
  2857. * @returns an array of indices indicating the offset of each attribute
  2858. */
  2859. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2860. var results = [];
  2861. for (var index = 0; index < attributesNames.length; index++) {
  2862. try {
  2863. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2864. } catch (e) {
  2865. results.push(-1);
  2866. }
  2867. }
  2868. return results;
  2869. }
  2870. /**
  2871. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2872. * @param effect defines the effect to activate
  2873. */
  2874. public enableEffect(effect: Nullable<Effect>): void {
  2875. if (!effect || effect === this._currentEffect) {
  2876. return;
  2877. }
  2878. // Use program
  2879. this.bindSamplers(effect);
  2880. this._currentEffect = effect;
  2881. if (effect.onBind) {
  2882. effect.onBind(effect);
  2883. }
  2884. if (effect._onBindObservable) {
  2885. effect._onBindObservable.notifyObservers(effect);
  2886. }
  2887. }
  2888. /**
  2889. * Set the value of an uniform to an array of int32
  2890. * @param uniform defines the webGL uniform location where to store the value
  2891. * @param array defines the array of int32 to store
  2892. */
  2893. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2894. if (!uniform)
  2895. return;
  2896. this._gl.uniform1iv(uniform, array);
  2897. }
  2898. /**
  2899. * Set the value of an uniform to an array of int32 (stored as vec2)
  2900. * @param uniform defines the webGL uniform location where to store the value
  2901. * @param array defines the array of int32 to store
  2902. */
  2903. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2904. if (!uniform || array.length % 2 !== 0)
  2905. return;
  2906. this._gl.uniform2iv(uniform, array);
  2907. }
  2908. /**
  2909. * Set the value of an uniform to an array of int32 (stored as vec3)
  2910. * @param uniform defines the webGL uniform location where to store the value
  2911. * @param array defines the array of int32 to store
  2912. */
  2913. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2914. if (!uniform || array.length % 3 !== 0)
  2915. return;
  2916. this._gl.uniform3iv(uniform, array);
  2917. }
  2918. /**
  2919. * Set the value of an uniform to an array of int32 (stored as vec4)
  2920. * @param uniform defines the webGL uniform location where to store the value
  2921. * @param array defines the array of int32 to store
  2922. */
  2923. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2924. if (!uniform || array.length % 4 !== 0)
  2925. return;
  2926. this._gl.uniform4iv(uniform, array);
  2927. }
  2928. /**
  2929. * Set the value of an uniform to an array of float32
  2930. * @param uniform defines the webGL uniform location where to store the value
  2931. * @param array defines the array of float32 to store
  2932. */
  2933. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2934. if (!uniform)
  2935. return;
  2936. this._gl.uniform1fv(uniform, array);
  2937. }
  2938. /**
  2939. * Set the value of an uniform to an array of float32 (stored as vec2)
  2940. * @param uniform defines the webGL uniform location where to store the value
  2941. * @param array defines the array of float32 to store
  2942. */
  2943. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2944. if (!uniform || array.length % 2 !== 0)
  2945. return;
  2946. this._gl.uniform2fv(uniform, array);
  2947. }
  2948. /**
  2949. * Set the value of an uniform to an array of float32 (stored as vec3)
  2950. * @param uniform defines the webGL uniform location where to store the value
  2951. * @param array defines the array of float32 to store
  2952. */
  2953. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2954. if (!uniform || array.length % 3 !== 0)
  2955. return;
  2956. this._gl.uniform3fv(uniform, array);
  2957. }
  2958. /**
  2959. * Set the value of an uniform to an array of float32 (stored as vec4)
  2960. * @param uniform defines the webGL uniform location where to store the value
  2961. * @param array defines the array of float32 to store
  2962. */
  2963. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2964. if (!uniform || array.length % 4 !== 0)
  2965. return;
  2966. this._gl.uniform4fv(uniform, array);
  2967. }
  2968. /**
  2969. * Set the value of an uniform to an array of number
  2970. * @param uniform defines the webGL uniform location where to store the value
  2971. * @param array defines the array of number to store
  2972. */
  2973. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2974. if (!uniform)
  2975. return;
  2976. this._gl.uniform1fv(uniform, <any>array);
  2977. }
  2978. /**
  2979. * Set the value of an uniform to an array of number (stored as vec2)
  2980. * @param uniform defines the webGL uniform location where to store the value
  2981. * @param array defines the array of number to store
  2982. */
  2983. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2984. if (!uniform || array.length % 2 !== 0)
  2985. return;
  2986. this._gl.uniform2fv(uniform, <any>array);
  2987. }
  2988. /**
  2989. * Set the value of an uniform to an array of number (stored as vec3)
  2990. * @param uniform defines the webGL uniform location where to store the value
  2991. * @param array defines the array of number to store
  2992. */
  2993. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2994. if (!uniform || array.length % 3 !== 0)
  2995. return;
  2996. this._gl.uniform3fv(uniform, <any>array);
  2997. }
  2998. /**
  2999. * Set the value of an uniform to an array of number (stored as vec4)
  3000. * @param uniform defines the webGL uniform location where to store the value
  3001. * @param array defines the array of number to store
  3002. */
  3003. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3004. if (!uniform || array.length % 4 !== 0)
  3005. return;
  3006. this._gl.uniform4fv(uniform, <any>array);
  3007. }
  3008. /**
  3009. * Set the value of an uniform to an array of float32 (stored as matrices)
  3010. * @param uniform defines the webGL uniform location where to store the value
  3011. * @param matrices defines the array of float32 to store
  3012. */
  3013. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  3014. if (!uniform)
  3015. return;
  3016. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3017. }
  3018. /**
  3019. * Set the value of an uniform to a matrix
  3020. * @param uniform defines the webGL uniform location where to store the value
  3021. * @param matrix defines the matrix to store
  3022. */
  3023. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  3024. if (!uniform)
  3025. return;
  3026. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3027. }
  3028. /**
  3029. * Set the value of an uniform to a matrix (3x3)
  3030. * @param uniform defines the webGL uniform location where to store the value
  3031. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  3032. */
  3033. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3034. if (!uniform)
  3035. return;
  3036. this._gl.uniformMatrix3fv(uniform, false, matrix);
  3037. }
  3038. /**
  3039. * Set the value of an uniform to a matrix (2x2)
  3040. * @param uniform defines the webGL uniform location where to store the value
  3041. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  3042. */
  3043. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3044. if (!uniform)
  3045. return;
  3046. this._gl.uniformMatrix2fv(uniform, false, matrix);
  3047. }
  3048. /**
  3049. * Set the value of an uniform to a number (int)
  3050. * @param uniform defines the webGL uniform location where to store the value
  3051. * @param value defines the int number to store
  3052. */
  3053. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3054. if (!uniform)
  3055. return;
  3056. this._gl.uniform1i(uniform, value);
  3057. }
  3058. /**
  3059. * Set the value of an uniform to a number (float)
  3060. * @param uniform defines the webGL uniform location where to store the value
  3061. * @param value defines the float number to store
  3062. */
  3063. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3064. if (!uniform)
  3065. return;
  3066. this._gl.uniform1f(uniform, value);
  3067. }
  3068. /**
  3069. * Set the value of an uniform to a vec2
  3070. * @param uniform defines the webGL uniform location where to store the value
  3071. * @param x defines the 1st component of the value
  3072. * @param y defines the 2nd component of the value
  3073. */
  3074. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3075. if (!uniform)
  3076. return;
  3077. this._gl.uniform2f(uniform, x, y);
  3078. }
  3079. /**
  3080. * Set the value of an uniform to a vec3
  3081. * @param uniform defines the webGL uniform location where to store the value
  3082. * @param x defines the 1st component of the value
  3083. * @param y defines the 2nd component of the value
  3084. * @param z defines the 3rd component of the value
  3085. */
  3086. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3087. if (!uniform)
  3088. return;
  3089. this._gl.uniform3f(uniform, x, y, z);
  3090. }
  3091. /**
  3092. * Set the value of an uniform to a boolean
  3093. * @param uniform defines the webGL uniform location where to store the value
  3094. * @param bool defines the boolean to store
  3095. */
  3096. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3097. if (!uniform)
  3098. return;
  3099. this._gl.uniform1i(uniform, bool);
  3100. }
  3101. /**
  3102. * Set the value of an uniform to a vec4
  3103. * @param uniform defines the webGL uniform location where to store the value
  3104. * @param x defines the 1st component of the value
  3105. * @param y defines the 2nd component of the value
  3106. * @param z defines the 3rd component of the value
  3107. * @param w defines the 4th component of the value
  3108. */
  3109. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3110. if (!uniform)
  3111. return;
  3112. this._gl.uniform4f(uniform, x, y, z, w);
  3113. }
  3114. /**
  3115. * Set the value of an uniform to a Color3
  3116. * @param uniform defines the webGL uniform location where to store the value
  3117. * @param color3 defines the color to store
  3118. */
  3119. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3120. if (!uniform)
  3121. return;
  3122. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3123. }
  3124. /**
  3125. * Set the value of an uniform to a Color3 and an alpha value
  3126. * @param uniform defines the webGL uniform location where to store the value
  3127. * @param color3 defines the color to store
  3128. * @param alpha defines the alpha component to store
  3129. */
  3130. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3131. if (!uniform)
  3132. return;
  3133. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3134. }
  3135. /**
  3136. * Sets a Color4 on a uniform variable
  3137. * @param uniform defines the uniform location
  3138. * @param color4 defines the value to be set
  3139. */
  3140. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3141. if (!uniform)
  3142. return;
  3143. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3144. }
  3145. // States
  3146. /**
  3147. * Set various states to the webGL context
  3148. * @param culling defines backface culling state
  3149. * @param zOffset defines the value to apply to zOffset (0 by default)
  3150. * @param force defines if states must be applied even if cache is up to date
  3151. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3152. */
  3153. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3154. // Culling
  3155. if (this._depthCullingState.cull !== culling || force) {
  3156. this._depthCullingState.cull = culling;
  3157. }
  3158. // Cull face
  3159. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3160. if (this._depthCullingState.cullFace !== cullFace || force) {
  3161. this._depthCullingState.cullFace = cullFace;
  3162. }
  3163. // Z offset
  3164. this.setZOffset(zOffset);
  3165. // Front face
  3166. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3167. if (this._depthCullingState.frontFace !== frontFace || force) {
  3168. this._depthCullingState.frontFace = frontFace;
  3169. }
  3170. }
  3171. /**
  3172. * Set the z offset to apply to current rendering
  3173. * @param value defines the offset to apply
  3174. */
  3175. public setZOffset(value: number): void {
  3176. this._depthCullingState.zOffset = value;
  3177. }
  3178. /**
  3179. * Gets the current value of the zOffset
  3180. * @returns the current zOffset state
  3181. */
  3182. public getZOffset(): number {
  3183. return this._depthCullingState.zOffset;
  3184. }
  3185. /**
  3186. * Enable or disable depth buffering
  3187. * @param enable defines the state to set
  3188. */
  3189. public setDepthBuffer(enable: boolean): void {
  3190. this._depthCullingState.depthTest = enable;
  3191. }
  3192. /**
  3193. * Gets a boolean indicating if depth writing is enabled
  3194. * @returns the current depth writing state
  3195. */
  3196. public getDepthWrite(): boolean {
  3197. return this._depthCullingState.depthMask;
  3198. }
  3199. /**
  3200. * Enable or disable depth writing
  3201. * @param enable defines the state to set
  3202. */
  3203. public setDepthWrite(enable: boolean): void {
  3204. this._depthCullingState.depthMask = enable;
  3205. }
  3206. /**
  3207. * Enable or disable color writing
  3208. * @param enable defines the state to set
  3209. */
  3210. public setColorWrite(enable: boolean): void {
  3211. this._gl.colorMask(enable, enable, enable, enable);
  3212. this._colorWrite = enable;
  3213. }
  3214. /**
  3215. * Gets a boolean indicating if color writing is enabled
  3216. * @returns the current color writing state
  3217. */
  3218. public getColorWrite(): boolean {
  3219. return this._colorWrite;
  3220. }
  3221. /**
  3222. * Sets alpha constants used by some alpha blending modes
  3223. * @param r defines the red component
  3224. * @param g defines the green component
  3225. * @param b defines the blue component
  3226. * @param a defines the alpha component
  3227. */
  3228. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3229. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3230. }
  3231. /**
  3232. * Sets the current alpha mode
  3233. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  3234. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3235. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3236. */
  3237. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3238. if (this._alphaMode === mode) {
  3239. return;
  3240. }
  3241. switch (mode) {
  3242. case Engine.ALPHA_DISABLE:
  3243. this._alphaState.alphaBlend = false;
  3244. break;
  3245. case Engine.ALPHA_PREMULTIPLIED:
  3246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3247. this._alphaState.alphaBlend = true;
  3248. break;
  3249. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3251. this._alphaState.alphaBlend = true;
  3252. break;
  3253. case Engine.ALPHA_COMBINE:
  3254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3255. this._alphaState.alphaBlend = true;
  3256. break;
  3257. case Engine.ALPHA_ONEONE:
  3258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3259. this._alphaState.alphaBlend = true;
  3260. break;
  3261. case Engine.ALPHA_ADD:
  3262. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3263. this._alphaState.alphaBlend = true;
  3264. break;
  3265. case Engine.ALPHA_SUBTRACT:
  3266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3267. this._alphaState.alphaBlend = true;
  3268. break;
  3269. case Engine.ALPHA_MULTIPLY:
  3270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3271. this._alphaState.alphaBlend = true;
  3272. break;
  3273. case Engine.ALPHA_MAXIMIZED:
  3274. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3275. this._alphaState.alphaBlend = true;
  3276. break;
  3277. case Engine.ALPHA_INTERPOLATE:
  3278. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3279. this._alphaState.alphaBlend = true;
  3280. break;
  3281. case Engine.ALPHA_SCREENMODE:
  3282. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3283. this._alphaState.alphaBlend = true;
  3284. break;
  3285. }
  3286. if (!noDepthWriteChange) {
  3287. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3288. }
  3289. this._alphaMode = mode;
  3290. }
  3291. /**
  3292. * Gets the current alpha mode
  3293. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3294. * @returns the current alpha mode
  3295. */
  3296. public getAlphaMode(): number {
  3297. return this._alphaMode;
  3298. }
  3299. // Textures
  3300. /**
  3301. * Clears the list of texture accessible through engine.
  3302. * This can help preventing texture load conflict due to name collision.
  3303. */
  3304. public clearInternalTexturesCache() {
  3305. this._internalTexturesCache = [];
  3306. }
  3307. /**
  3308. * Force the entire cache to be cleared
  3309. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3310. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3311. */
  3312. public wipeCaches(bruteForce?: boolean): void {
  3313. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3314. return;
  3315. }
  3316. this._currentEffect = null;
  3317. this._unpackFlipYCached = null;
  3318. this._viewportCached.x = 0;
  3319. this._viewportCached.y = 0;
  3320. this._viewportCached.z = 0;
  3321. this._viewportCached.w = 0;
  3322. if (bruteForce) {
  3323. this.resetTextureCache();
  3324. this._currentProgram = null;
  3325. this._stencilState.reset();
  3326. this._depthCullingState.reset();
  3327. this.setDepthFunctionToLessOrEqual();
  3328. this._alphaState.reset();
  3329. }
  3330. this._resetVertexBufferBinding();
  3331. this._cachedIndexBuffer = null;
  3332. this._cachedEffectForVertexBuffers = null;
  3333. this._unbindVertexArrayObject();
  3334. this.bindIndexBuffer(null);
  3335. }
  3336. /**
  3337. * Set the compressed texture format to use, based on the formats you have, and the formats
  3338. * supported by the hardware / browser.
  3339. *
  3340. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3341. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3342. * to API arguments needed to compressed textures. This puts the burden on the container
  3343. * generator to house the arcane code for determining these for current & future formats.
  3344. *
  3345. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3346. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3347. *
  3348. * Note: The result of this call is not taken into account when a texture is base64.
  3349. *
  3350. * @param formatsAvailable defines the list of those format families you have created
  3351. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3352. *
  3353. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3354. * @returns The extension selected.
  3355. */
  3356. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3357. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3358. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3359. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3360. return this._textureFormatInUse = this._texturesSupported[i];
  3361. }
  3362. }
  3363. }
  3364. // actively set format to nothing, to allow this to be called more than once
  3365. // and possibly fail the 2nd time
  3366. this._textureFormatInUse = null;
  3367. return null;
  3368. }
  3369. private _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3370. var gl = this._gl;
  3371. var magFilter = gl.NEAREST;
  3372. var minFilter = gl.NEAREST;
  3373. switch (samplingMode) {
  3374. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  3375. magFilter = gl.LINEAR;
  3376. if (generateMipMaps) {
  3377. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3378. } else {
  3379. minFilter = gl.LINEAR;
  3380. }
  3381. break;
  3382. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  3383. magFilter = gl.LINEAR;
  3384. if (generateMipMaps) {
  3385. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3386. } else {
  3387. minFilter = gl.LINEAR;
  3388. }
  3389. break;
  3390. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  3391. magFilter = gl.NEAREST;
  3392. if (generateMipMaps) {
  3393. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3394. } else {
  3395. minFilter = gl.NEAREST;
  3396. }
  3397. break;
  3398. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  3399. magFilter = gl.NEAREST;
  3400. if (generateMipMaps) {
  3401. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3402. } else {
  3403. minFilter = gl.NEAREST;
  3404. }
  3405. break;
  3406. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  3407. magFilter = gl.NEAREST;
  3408. if (generateMipMaps) {
  3409. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3410. } else {
  3411. minFilter = gl.LINEAR;
  3412. }
  3413. break;
  3414. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  3415. magFilter = gl.NEAREST;
  3416. if (generateMipMaps) {
  3417. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3418. } else {
  3419. minFilter = gl.LINEAR;
  3420. }
  3421. break;
  3422. case Engine.TEXTURE_NEAREST_LINEAR:
  3423. magFilter = gl.NEAREST;
  3424. minFilter = gl.LINEAR;
  3425. break;
  3426. case Engine.TEXTURE_NEAREST_NEAREST:
  3427. magFilter = gl.NEAREST;
  3428. minFilter = gl.NEAREST;
  3429. break;
  3430. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  3431. magFilter = gl.LINEAR;
  3432. if (generateMipMaps) {
  3433. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3434. } else {
  3435. minFilter = gl.NEAREST;
  3436. }
  3437. break;
  3438. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  3439. magFilter = gl.LINEAR;
  3440. if (generateMipMaps) {
  3441. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3442. } else {
  3443. minFilter = gl.NEAREST;
  3444. }
  3445. break;
  3446. case Engine.TEXTURE_LINEAR_LINEAR:
  3447. magFilter = gl.LINEAR;
  3448. minFilter = gl.LINEAR;
  3449. break;
  3450. case Engine.TEXTURE_LINEAR_NEAREST:
  3451. magFilter = gl.LINEAR;
  3452. minFilter = gl.NEAREST;
  3453. break;
  3454. }
  3455. return {
  3456. min: minFilter,
  3457. mag: magFilter
  3458. }
  3459. }
  3460. private _partialLoadImg(url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  3461. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) {
  3462. var img: HTMLImageElement;
  3463. var onload = () => {
  3464. loadedImages[index] = img;
  3465. (<any>loadedImages)._internalCount++;
  3466. if (scene) {
  3467. scene._removePendingData(img);
  3468. }
  3469. if ((<any>loadedImages)._internalCount === 6) {
  3470. onfinish(loadedImages);
  3471. }
  3472. };
  3473. var onerror = (message?: string, exception?: any) => {
  3474. if (scene) {
  3475. scene._removePendingData(img);
  3476. }
  3477. if (onErrorCallBack) {
  3478. onErrorCallBack(message, exception);
  3479. }
  3480. };
  3481. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  3482. if (scene) {
  3483. scene._addPendingData(img);
  3484. }
  3485. }
  3486. private _cascadeLoadImgs(rootUrl: string, scene: Nullable<Scene>,
  3487. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) {
  3488. var loadedImages: HTMLImageElement[] = [];
  3489. (<any>loadedImages)._internalCount = 0;
  3490. for (let index = 0; index < 6; index++) {
  3491. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  3492. }
  3493. };
  3494. /** @hidden */
  3495. public _createTexture(): WebGLTexture {
  3496. let texture = this._gl.createTexture();
  3497. if (!texture) {
  3498. throw new Error("Unable to create texture");
  3499. }
  3500. return texture;
  3501. }
  3502. /**
  3503. * Usually called from BABYLON.Texture.ts.
  3504. * Passed information to create a WebGLTexture
  3505. * @param urlArg defines a value which contains one of the following:
  3506. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3507. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3508. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3509. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3510. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  3511. * @param scene needed for loading to the correct scene
  3512. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  3513. * @param onLoad optional callback to be called upon successful completion
  3514. * @param onError optional callback to be called upon failure
  3515. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  3516. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3517. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3518. * @param forcedExtension defines the extension to use to pick the right loader
  3519. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3520. */
  3521. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  3522. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3523. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  3524. forcedExtension: Nullable<string> = null): InternalTexture {
  3525. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3526. var fromData = url.substr(0, 5) === "data:";
  3527. var fromBlob = url.substr(0, 5) === "blob:";
  3528. var isBase64 = fromData && url.indexOf("base64") !== -1;
  3529. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3530. // establish the file extension, if possible
  3531. var lastDot = url.lastIndexOf('.');
  3532. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  3533. let loader: Nullable<IInternalTextureLoader> = null;
  3534. for (let availableLoader of Engine._TextureLoaders) {
  3535. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  3536. loader = availableLoader;
  3537. break;
  3538. }
  3539. }
  3540. if (loader) {
  3541. url = loader.transformUrl(url, this._textureFormatInUse);
  3542. }
  3543. if (scene) {
  3544. scene._addPendingData(texture);
  3545. }
  3546. texture.url = url;
  3547. texture.generateMipMaps = !noMipmap;
  3548. texture.samplingMode = samplingMode;
  3549. texture.invertY = invertY;
  3550. if (!this._doNotHandleContextLost) {
  3551. // Keep a link to the buffer only if we plan to handle context lost
  3552. texture._buffer = buffer;
  3553. }
  3554. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3555. if (onLoad && !fallback) {
  3556. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3557. }
  3558. if (!fallback) this._internalTexturesCache.push(texture);
  3559. let onInternalError = (message?: string, exception?: any) => {
  3560. if (scene) {
  3561. scene._removePendingData(texture);
  3562. }
  3563. let customFallback = false;
  3564. if (loader) {
  3565. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  3566. if (fallbackUrl) {
  3567. // Add Back
  3568. customFallback = true;
  3569. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3570. }
  3571. }
  3572. if (!customFallback) {
  3573. if (onLoadObserver) {
  3574. texture.onLoadedObservable.remove(onLoadObserver);
  3575. }
  3576. if (Tools.UseFallbackTexture) {
  3577. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3578. }
  3579. }
  3580. if (onError) {
  3581. onError(message || "Unknown error", exception);
  3582. }
  3583. }
  3584. // processing for non-image formats
  3585. if (loader) {
  3586. var callback = (data: string | ArrayBuffer) => {
  3587. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
  3588. this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  3589. done();
  3590. return false;
  3591. },
  3592. samplingMode);
  3593. });
  3594. }
  3595. if (!buffer) {
  3596. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3597. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  3598. });
  3599. } else {
  3600. callback(buffer as ArrayBuffer);
  3601. }
  3602. } else {
  3603. var onload = (img: HTMLImageElement) => {
  3604. if (fromBlob && !this._doNotHandleContextLost) {
  3605. // We need to store the image if we need to rebuild the texture
  3606. // in case of a webgl context lost
  3607. texture._buffer = img;
  3608. }
  3609. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3610. let gl = this._gl;
  3611. var isPot = (img.width === potWidth && img.height === potHeight);
  3612. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3613. if (isPot) {
  3614. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3615. return false;
  3616. }
  3617. let maxTextureSize = this._caps.maxTextureSize;
  3618. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  3619. this._prepareWorkingCanvas();
  3620. if (!this._workingCanvas || !this._workingContext) {
  3621. return false;
  3622. }
  3623. this._workingCanvas.width = potWidth;
  3624. this._workingCanvas.height = potHeight;
  3625. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3626. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3627. texture.width = potWidth;
  3628. texture.height = potHeight;
  3629. return false;
  3630. } else {
  3631. // Using shaders when possible to rescale because canvas.drawImage is lossy
  3632. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3633. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3634. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3639. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3640. this._releaseTexture(source);
  3641. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3642. continuationCallback();
  3643. });
  3644. }
  3645. return true;
  3646. }, samplingMode);
  3647. };
  3648. if (!fromData || isBase64) {
  3649. if (buffer instanceof HTMLImageElement) {
  3650. onload(buffer);
  3651. } else {
  3652. Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  3653. }
  3654. }
  3655. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3656. Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  3657. }
  3658. else {
  3659. onload(<HTMLImageElement>buffer);
  3660. }
  3661. }
  3662. return texture;
  3663. }
  3664. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3665. let rtt = this.createRenderTargetTexture({
  3666. width: destination.width,
  3667. height: destination.height,
  3668. }, {
  3669. generateMipMaps: false,
  3670. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3671. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  3672. generateDepthBuffer: false,
  3673. generateStencilBuffer: false
  3674. }
  3675. );
  3676. if (!this._rescalePostProcess) {
  3677. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3678. }
  3679. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3680. this._rescalePostProcess.onApply = function (effect) {
  3681. effect._bindTexture("textureSampler", source);
  3682. }
  3683. let hostingScene = scene;
  3684. if (!hostingScene) {
  3685. hostingScene = this.scenes[this.scenes.length - 1];
  3686. }
  3687. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3688. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3689. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3690. this.unBindFramebuffer(rtt);
  3691. this._releaseTexture(rtt);
  3692. if (onComplete) {
  3693. onComplete();
  3694. }
  3695. });
  3696. }
  3697. /**
  3698. * Update a raw texture
  3699. * @param texture defines the texture to update
  3700. * @param data defines the data to store in the texture
  3701. * @param format defines the format of the data
  3702. * @param invertY defines if data must be stored with Y axis inverted
  3703. * @param compression defines the compression used (null by default)
  3704. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3705. */
  3706. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  3707. if (!texture) {
  3708. return;
  3709. }
  3710. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  3711. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3712. // babylon's internalFormat but gl's texImage2D format
  3713. var internalFormat = this._getInternalFormat(format);
  3714. var textureType = this._getWebGLTextureType(type);
  3715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3716. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3717. if (!this._doNotHandleContextLost) {
  3718. texture._bufferView = data;
  3719. texture.format = format;
  3720. texture.type = type;
  3721. texture.invertY = invertY;
  3722. texture._compression = compression;
  3723. }
  3724. if (texture.width % 4 !== 0) {
  3725. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3726. }
  3727. if (compression && data) {
  3728. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3729. } else {
  3730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3731. }
  3732. if (texture.generateMipMaps) {
  3733. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3734. }
  3735. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3736. // this.resetTextureCache();
  3737. texture.isReady = true;
  3738. }
  3739. /**
  3740. * Creates a raw texture
  3741. * @param data defines the data to store in the texture
  3742. * @param width defines the width of the texture
  3743. * @param height defines the height of the texture
  3744. * @param format defines the format of the data
  3745. * @param generateMipMaps defines if the engine should generate the mip levels
  3746. * @param invertY defines if data must be stored with Y axis inverted
  3747. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3748. * @param compression defines the compression used (null by default)
  3749. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3750. * @returns the raw texture inside an InternalTexture
  3751. */
  3752. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3753. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3754. texture.baseWidth = width;
  3755. texture.baseHeight = height;
  3756. texture.width = width;
  3757. texture.height = height;
  3758. texture.format = format;
  3759. texture.generateMipMaps = generateMipMaps;
  3760. texture.samplingMode = samplingMode;
  3761. texture.invertY = invertY;
  3762. texture._compression = compression;
  3763. texture.type = type;
  3764. if (!this._doNotHandleContextLost) {
  3765. texture._bufferView = data;
  3766. }
  3767. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3769. // Filters
  3770. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  3771. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3772. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3773. if (generateMipMaps) {
  3774. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3775. }
  3776. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3777. this._internalTexturesCache.push(texture);
  3778. return texture;
  3779. }
  3780. private _unpackFlipYCached: Nullable<boolean> = null;
  3781. /** @hidden */
  3782. public _unpackFlipY(value: boolean) {
  3783. if (this._unpackFlipYCached !== value) {
  3784. this._unpackFlipYCached = value;
  3785. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  3786. }
  3787. }
  3788. /** @hidden */
  3789. public _getUnpackAlignement(): number {
  3790. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  3791. }
  3792. /**
  3793. * Creates a dynamic texture
  3794. * @param width defines the width of the texture
  3795. * @param height defines the height of the texture
  3796. * @param generateMipMaps defines if the engine should generate the mip levels
  3797. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3798. * @returns the dynamic texture inside an InternalTexture
  3799. */
  3800. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3801. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  3802. texture.baseWidth = width;
  3803. texture.baseHeight = height;
  3804. if (generateMipMaps) {
  3805. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3806. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3807. }
  3808. // this.resetTextureCache();
  3809. texture.width = width;
  3810. texture.height = height;
  3811. texture.isReady = false;
  3812. texture.generateMipMaps = generateMipMaps;
  3813. texture.samplingMode = samplingMode;
  3814. this.updateTextureSamplingMode(samplingMode, texture);
  3815. this._internalTexturesCache.push(texture);
  3816. return texture;
  3817. }
  3818. /**
  3819. * Update the sampling mode of a given texture
  3820. * @param samplingMode defines the required sampling mode
  3821. * @param texture defines the texture to update
  3822. */
  3823. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3824. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  3825. if (texture.isCube) {
  3826. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3827. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3829. } else if (texture.is3D) {
  3830. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3831. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3832. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3833. } else {
  3834. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3835. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3836. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3837. }
  3838. texture.samplingMode = samplingMode;
  3839. }
  3840. /**
  3841. * Update the content of a dynamic texture
  3842. * @param texture defines the texture to update
  3843. * @param canvas defines the canvas containing the source
  3844. * @param invertY defines if data must be stored with Y axis inverted
  3845. * @param premulAlpha defines if alpha is stored as premultiplied
  3846. * @param format defines the format of the data
  3847. */
  3848. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  3849. if (!texture) {
  3850. return;
  3851. }
  3852. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3853. this._unpackFlipY(invertY);
  3854. if (premulAlpha) {
  3855. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3856. }
  3857. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3858. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3859. if (texture.generateMipMaps) {
  3860. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3861. }
  3862. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3863. if (premulAlpha) {
  3864. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3865. }
  3866. texture.isReady = true;
  3867. }
  3868. /**
  3869. * Update a video texture
  3870. * @param texture defines the texture to update
  3871. * @param video defines the video element to use
  3872. * @param invertY defines if data must be stored with Y axis inverted
  3873. */
  3874. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  3875. if (!texture || texture._isDisabled) {
  3876. return;
  3877. }
  3878. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3879. this._unpackFlipY(!invertY); // Video are upside down by default
  3880. try {
  3881. // Testing video texture support
  3882. if (this._videoTextureSupported === undefined) {
  3883. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3884. if (this._gl.getError() !== 0) {
  3885. this._videoTextureSupported = false;
  3886. } else {
  3887. this._videoTextureSupported = true;
  3888. }
  3889. }
  3890. // Copy video through the current working canvas if video texture is not supported
  3891. if (!this._videoTextureSupported) {
  3892. if (!texture._workingCanvas) {
  3893. texture._workingCanvas = document.createElement("canvas");
  3894. let context = texture._workingCanvas.getContext("2d");
  3895. if (!context) {
  3896. throw new Error("Unable to get 2d context");
  3897. }
  3898. texture._workingContext = context;
  3899. texture._workingCanvas.width = texture.width;
  3900. texture._workingCanvas.height = texture.height;
  3901. }
  3902. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  3903. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3904. } else {
  3905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3906. }
  3907. if (texture.generateMipMaps) {
  3908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3909. }
  3910. if (!wasPreviouslyBound) {
  3911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3912. }
  3913. // this.resetTextureCache();
  3914. texture.isReady = true;
  3915. } catch (ex) {
  3916. // Something unexpected
  3917. // Let's disable the texture
  3918. texture._isDisabled = true;
  3919. }
  3920. }
  3921. /**
  3922. * Updates a depth texture Comparison Mode and Function.
  3923. * If the comparison Function is equal to 0, the mode will be set to none.
  3924. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  3925. * @param texture The texture to set the comparison function for
  3926. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  3927. */
  3928. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3929. if (this.webGLVersion === 1) {
  3930. Tools.Error("WebGL 1 does not support texture comparison.");
  3931. return;
  3932. }
  3933. var gl = this._gl;
  3934. if (texture.isCube) {
  3935. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3936. if (comparisonFunction === 0) {
  3937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3939. }
  3940. else {
  3941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3943. }
  3944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3945. } else {
  3946. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3947. if (comparisonFunction === 0) {
  3948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3950. }
  3951. else {
  3952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3954. }
  3955. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3956. }
  3957. texture._comparisonFunction = comparisonFunction;
  3958. }
  3959. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3960. var width = (<{ width: number, height: number }>size).width || <number>size;
  3961. var height = (<{ width: number, height: number }>size).height || <number>size;
  3962. internalTexture.baseWidth = width;
  3963. internalTexture.baseHeight = height;
  3964. internalTexture.width = width;
  3965. internalTexture.height = height;
  3966. internalTexture.isReady = true;
  3967. internalTexture.samples = 1;
  3968. internalTexture.generateMipMaps = false;
  3969. internalTexture._generateDepthBuffer = true;
  3970. internalTexture._generateStencilBuffer = generateStencil;
  3971. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  3972. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3973. internalTexture._comparisonFunction = comparisonFunction;
  3974. var gl = this._gl;
  3975. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3976. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  3977. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3978. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3979. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3980. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3981. if (comparisonFunction === 0) {
  3982. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3983. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3984. }
  3985. else {
  3986. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3987. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3988. }
  3989. }
  3990. /**
  3991. * Creates a depth stencil texture.
  3992. * This is only available in WebGL 2 or with the depth texture extension available.
  3993. * @param size The size of face edge in the texture.
  3994. * @param options The options defining the texture.
  3995. * @returns The texture
  3996. */
  3997. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3998. if (options.isCube) {
  3999. let width = (<{ width: number, height: number }>size).width || <number>size;
  4000. return this._createDepthStencilCubeTexture(width, options);
  4001. }
  4002. else {
  4003. return this._createDepthStencilTexture(size, options);
  4004. }
  4005. }
  4006. /**
  4007. * Creates a depth stencil texture.
  4008. * This is only available in WebGL 2 or with the depth texture extension available.
  4009. * @param size The size of face edge in the texture.
  4010. * @param options The options defining the texture.
  4011. * @returns The texture
  4012. */
  4013. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  4014. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  4015. if (!this._caps.depthTextureExtension) {
  4016. Tools.Error("Depth texture is not supported by your browser or hardware.");
  4017. return internalTexture;
  4018. }
  4019. var internalOptions = {
  4020. bilinearFiltering: false,
  4021. comparisonFunction: 0,
  4022. generateStencil: false,
  4023. ...options
  4024. }
  4025. var gl = this._gl;
  4026. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  4027. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4028. if (this.webGLVersion > 1) {
  4029. if (internalOptions.generateStencil) {
  4030. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4031. }
  4032. else {
  4033. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4034. }
  4035. }
  4036. else {
  4037. if (internalOptions.generateStencil) {
  4038. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4039. }
  4040. else {
  4041. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4042. }
  4043. }
  4044. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4045. return internalTexture;
  4046. }
  4047. /**
  4048. * Creates a depth stencil cube texture.
  4049. * This is only available in WebGL 2.
  4050. * @param size The size of face edge in the cube texture.
  4051. * @param options The options defining the cube texture.
  4052. * @returns The cube texture
  4053. */
  4054. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  4055. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4056. internalTexture.isCube = true;
  4057. if (this.webGLVersion === 1) {
  4058. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4059. return internalTexture;
  4060. }
  4061. var internalOptions = {
  4062. bilinearFiltering: false,
  4063. comparisonFunction: 0,
  4064. generateStencil: false,
  4065. ...options
  4066. }
  4067. var gl = this._gl;
  4068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4069. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4070. // Create the depth/stencil buffer
  4071. for (var face = 0; face < 6; face++) {
  4072. if (internalOptions.generateStencil) {
  4073. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4074. }
  4075. else {
  4076. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4077. }
  4078. }
  4079. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4080. return internalTexture;
  4081. }
  4082. /**
  4083. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4084. * @param renderTarget The render target to set the frame buffer for
  4085. */
  4086. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4087. // Create the framebuffer
  4088. var internalTexture = renderTarget.getInternalTexture();
  4089. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4090. return;
  4091. }
  4092. var gl = this._gl;
  4093. var depthStencilTexture = renderTarget.depthStencilTexture;
  4094. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4095. if (depthStencilTexture.isCube) {
  4096. if (depthStencilTexture._generateStencilBuffer) {
  4097. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4098. }
  4099. else {
  4100. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4101. }
  4102. }
  4103. else {
  4104. if (depthStencilTexture._generateStencilBuffer) {
  4105. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4106. }
  4107. else {
  4108. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4109. }
  4110. }
  4111. this.bindUnboundFramebuffer(null);
  4112. }
  4113. /**
  4114. * Creates a new render target texture
  4115. * @param size defines the size of the texture
  4116. * @param options defines the options used to create the texture
  4117. * @returns a new render target texture stored in an InternalTexture
  4118. */
  4119. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4120. let fullOptions = new RenderTargetCreationOptions();
  4121. if (options !== undefined && typeof options === "object") {
  4122. fullOptions.generateMipMaps = options.generateMipMaps;
  4123. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4124. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4125. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4126. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4127. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4128. } else {
  4129. fullOptions.generateMipMaps = <boolean>options;
  4130. fullOptions.generateDepthBuffer = true;
  4131. fullOptions.generateStencilBuffer = false;
  4132. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4133. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4134. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4135. }
  4136. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4137. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4138. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4139. }
  4140. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4141. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4142. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4143. }
  4144. var gl = this._gl;
  4145. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4146. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4147. var width = (<{ width: number, height: number }>size).width || <number>size;
  4148. var height = (<{ width: number, height: number }>size).height || <number>size;
  4149. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  4150. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4151. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4152. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4153. }
  4154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4158. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4159. // Create the framebuffer
  4160. var currentFrameBuffer = this._currentFramebuffer;
  4161. var framebuffer = gl.createFramebuffer();
  4162. this.bindUnboundFramebuffer(framebuffer);
  4163. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4164. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4165. if (fullOptions.generateMipMaps) {
  4166. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4167. }
  4168. // Unbind
  4169. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4170. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4171. this.bindUnboundFramebuffer(currentFrameBuffer);
  4172. texture._framebuffer = framebuffer;
  4173. texture.baseWidth = width;
  4174. texture.baseHeight = height;
  4175. texture.width = width;
  4176. texture.height = height;
  4177. texture.isReady = true;
  4178. texture.samples = 1;
  4179. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4180. texture.samplingMode = fullOptions.samplingMode;
  4181. texture.type = fullOptions.type;
  4182. texture.format = fullOptions.format;
  4183. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4184. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4185. // this.resetTextureCache();
  4186. this._internalTexturesCache.push(texture);
  4187. return texture;
  4188. }
  4189. /**
  4190. * Create a multi render target texture
  4191. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4192. * @param size defines the size of the texture
  4193. * @param options defines the creation options
  4194. * @returns the cube texture as an InternalTexture
  4195. */
  4196. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4197. var generateMipMaps = false;
  4198. var generateDepthBuffer = true;
  4199. var generateStencilBuffer = false;
  4200. var generateDepthTexture = false;
  4201. var textureCount = 1;
  4202. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4203. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4204. var types = new Array<number>();
  4205. var samplingModes = new Array<number>();
  4206. if (options !== undefined) {
  4207. generateMipMaps = options.generateMipMaps === undefined ? false: options.generateMipMaps;
  4208. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4209. generateStencilBuffer = options.generateStencilBuffer === undefined ? false: options.generateStencilBuffer;
  4210. generateDepthTexture = options.generateDepthTexture === undefined ? false: options.generateDepthTexture;
  4211. textureCount = options.textureCount || 1;
  4212. if (options.types) {
  4213. types = options.types;
  4214. }
  4215. if (options.samplingModes) {
  4216. samplingModes = options.samplingModes;
  4217. }
  4218. }
  4219. var gl = this._gl;
  4220. // Create the framebuffer
  4221. var framebuffer = gl.createFramebuffer();
  4222. this.bindUnboundFramebuffer(framebuffer);
  4223. var width = size.width || size;
  4224. var height = size.height || size;
  4225. var textures = [];
  4226. var attachments = []
  4227. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4228. for (var i = 0; i < textureCount; i++) {
  4229. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4230. var type = types[i] || defaultType;
  4231. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4232. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4233. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4234. }
  4235. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4236. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4237. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4238. }
  4239. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4240. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4241. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4242. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4243. }
  4244. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4245. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4246. textures.push(texture);
  4247. attachments.push(attachment);
  4248. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4249. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4254. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4255. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4256. if (generateMipMaps) {
  4257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4258. }
  4259. // Unbind
  4260. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4261. texture._framebuffer = framebuffer;
  4262. texture._depthStencilBuffer = depthStencilBuffer;
  4263. texture.baseWidth = width;
  4264. texture.baseHeight = height;
  4265. texture.width = width;
  4266. texture.height = height;
  4267. texture.isReady = true;
  4268. texture.samples = 1;
  4269. texture.generateMipMaps = generateMipMaps;
  4270. texture.samplingMode = samplingMode;
  4271. texture.type = type;
  4272. texture._generateDepthBuffer = generateDepthBuffer;
  4273. texture._generateStencilBuffer = generateStencilBuffer;
  4274. texture._attachments = attachments;
  4275. this._internalTexturesCache.push(texture);
  4276. }
  4277. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4278. // Depth texture
  4279. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4280. gl.activeTexture(gl.TEXTURE0);
  4281. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4286. gl.texImage2D(
  4287. gl.TEXTURE_2D,
  4288. 0,
  4289. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4290. width,
  4291. height,
  4292. 0,
  4293. gl.DEPTH_COMPONENT,
  4294. gl.UNSIGNED_SHORT,
  4295. null
  4296. );
  4297. gl.framebufferTexture2D(
  4298. gl.FRAMEBUFFER,
  4299. gl.DEPTH_ATTACHMENT,
  4300. gl.TEXTURE_2D,
  4301. depthTexture._webGLTexture,
  4302. 0
  4303. );
  4304. depthTexture._framebuffer = framebuffer;
  4305. depthTexture.baseWidth = width;
  4306. depthTexture.baseHeight = height;
  4307. depthTexture.width = width;
  4308. depthTexture.height = height;
  4309. depthTexture.isReady = true;
  4310. depthTexture.samples = 1;
  4311. depthTexture.generateMipMaps = generateMipMaps;
  4312. depthTexture.samplingMode = gl.NEAREST;
  4313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4315. textures.push(depthTexture)
  4316. this._internalTexturesCache.push(depthTexture);
  4317. }
  4318. gl.drawBuffers(attachments);
  4319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4320. this.bindUnboundFramebuffer(null);
  4321. this.resetTextureCache();
  4322. return textures;
  4323. }
  4324. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4325. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4326. var gl = this._gl;
  4327. // Create the depth/stencil buffer
  4328. if (generateStencilBuffer) {
  4329. depthStencilBuffer = gl.createRenderbuffer();
  4330. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4331. if (samples > 1) {
  4332. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4333. } else {
  4334. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4335. }
  4336. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4337. }
  4338. else if (generateDepthBuffer) {
  4339. depthStencilBuffer = gl.createRenderbuffer();
  4340. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4341. if (samples > 1) {
  4342. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4343. } else {
  4344. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4345. }
  4346. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4347. }
  4348. return depthStencilBuffer;
  4349. }
  4350. /**
  4351. * Updates the sample count of a render target texture
  4352. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4353. * @param texture defines the texture to update
  4354. * @param samples defines the sample count to set
  4355. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4356. */
  4357. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4358. if (this.webGLVersion < 2 || !texture) {
  4359. return 1;
  4360. }
  4361. if (texture.samples === samples) {
  4362. return samples;
  4363. }
  4364. var gl = this._gl;
  4365. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4366. // Dispose previous render buffers
  4367. if (texture._depthStencilBuffer) {
  4368. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4369. texture._depthStencilBuffer = null;
  4370. }
  4371. if (texture._MSAAFramebuffer) {
  4372. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4373. texture._MSAAFramebuffer = null;
  4374. }
  4375. if (texture._MSAARenderBuffer) {
  4376. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4377. texture._MSAARenderBuffer = null;
  4378. }
  4379. if (samples > 1) {
  4380. let framebuffer = gl.createFramebuffer();
  4381. if (!framebuffer) {
  4382. throw new Error("Unable to create multi sampled framebuffer");
  4383. }
  4384. texture._MSAAFramebuffer = framebuffer;
  4385. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4386. var colorRenderbuffer = gl.createRenderbuffer();
  4387. if (!colorRenderbuffer) {
  4388. throw new Error("Unable to create multi sampled framebuffer");
  4389. }
  4390. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4391. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4392. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4393. texture._MSAARenderBuffer = colorRenderbuffer;
  4394. } else {
  4395. this.bindUnboundFramebuffer(texture._framebuffer);
  4396. }
  4397. texture.samples = samples;
  4398. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4399. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4400. this.bindUnboundFramebuffer(null);
  4401. return samples;
  4402. }
  4403. /**
  4404. * Update the sample count for a given multiple render target texture
  4405. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4406. * @param textures defines the textures to update
  4407. * @param samples defines the sample count to set
  4408. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4409. */
  4410. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4411. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4412. return 1;
  4413. }
  4414. if (textures[0].samples === samples) {
  4415. return samples;
  4416. }
  4417. var gl = this._gl;
  4418. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4419. // Dispose previous render buffers
  4420. if (textures[0]._depthStencilBuffer) {
  4421. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4422. textures[0]._depthStencilBuffer = null;
  4423. }
  4424. if (textures[0]._MSAAFramebuffer) {
  4425. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4426. textures[0]._MSAAFramebuffer = null;
  4427. }
  4428. for (var i = 0; i < textures.length; i++) {
  4429. if (textures[i]._MSAARenderBuffer) {
  4430. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4431. textures[i]._MSAARenderBuffer = null;
  4432. }
  4433. }
  4434. if (samples > 1) {
  4435. let framebuffer = gl.createFramebuffer();
  4436. if (!framebuffer) {
  4437. throw new Error("Unable to create multi sampled framebuffer");
  4438. }
  4439. this.bindUnboundFramebuffer(framebuffer);
  4440. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4441. var attachments = [];
  4442. for (var i = 0; i < textures.length; i++) {
  4443. var texture = textures[i];
  4444. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4445. var colorRenderbuffer = gl.createRenderbuffer();
  4446. if (!colorRenderbuffer) {
  4447. throw new Error("Unable to create multi sampled framebuffer");
  4448. }
  4449. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4450. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4451. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4452. texture._MSAAFramebuffer = framebuffer;
  4453. texture._MSAARenderBuffer = colorRenderbuffer;
  4454. texture.samples = samples;
  4455. texture._depthStencilBuffer = depthStencilBuffer;
  4456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4457. attachments.push(attachment);
  4458. }
  4459. gl.drawBuffers(attachments);
  4460. } else {
  4461. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4462. }
  4463. this.bindUnboundFramebuffer(null);
  4464. return samples;
  4465. }
  4466. /** @hidden */
  4467. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  4468. var gl = this._gl;
  4469. var target = gl.TEXTURE_2D;
  4470. if (texture.isCube) {
  4471. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4472. }
  4473. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4474. }
  4475. /** @hidden */
  4476. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4477. var gl = this._gl;
  4478. var textureType = this._getWebGLTextureType(texture.type);
  4479. var format = this._getInternalFormat(texture.format);
  4480. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4481. this._unpackFlipY(texture.invertY);
  4482. var target = gl.TEXTURE_2D;
  4483. if (texture.isCube) {
  4484. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4485. }
  4486. const lodMaxWidth = Math.round(Scalar.Log2(texture.width));
  4487. const lodMaxHeight = Math.round(Scalar.Log2(texture.height));
  4488. const width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  4489. const height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  4490. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  4491. }
  4492. /** @hidden */
  4493. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4494. var gl = this._gl;
  4495. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4496. this._bindTextureDirectly(bindTarget, texture, true);
  4497. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  4498. this._bindTextureDirectly(bindTarget, null, true);
  4499. }
  4500. /** @hidden */
  4501. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  4502. var gl = this._gl;
  4503. var textureType = this._getWebGLTextureType(texture.type);
  4504. var format = this._getInternalFormat(texture.format);
  4505. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4506. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4507. this._bindTextureDirectly(bindTarget, texture, true);
  4508. this._unpackFlipY(texture.invertY);
  4509. var target = gl.TEXTURE_2D;
  4510. if (texture.isCube) {
  4511. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4512. }
  4513. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  4514. this._bindTextureDirectly(bindTarget, null, true);
  4515. }
  4516. /**
  4517. * Creates a new render target cube texture
  4518. * @param size defines the size of the texture
  4519. * @param options defines the options used to create the texture
  4520. * @returns a new render target cube texture stored in an InternalTexture
  4521. */
  4522. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4523. let fullOptions = {
  4524. generateMipMaps: true,
  4525. generateDepthBuffer: true,
  4526. generateStencilBuffer: false,
  4527. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4528. samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4529. format: Engine.TEXTUREFORMAT_RGBA,
  4530. ...options
  4531. };
  4532. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4533. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4534. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4535. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4536. }
  4537. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4538. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4539. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4540. }
  4541. var gl = this._gl
  4542. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4543. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4544. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  4545. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4546. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4547. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4548. }
  4549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4553. for (var face = 0; face < 6; face++) {
  4554. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4555. }
  4556. // Create the framebuffer
  4557. var framebuffer = gl.createFramebuffer();
  4558. this.bindUnboundFramebuffer(framebuffer);
  4559. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4560. // MipMaps
  4561. if (fullOptions.generateMipMaps) {
  4562. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4563. }
  4564. // Unbind
  4565. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4566. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4567. this.bindUnboundFramebuffer(null);
  4568. texture._framebuffer = framebuffer;
  4569. texture.width = size;
  4570. texture.height = size;
  4571. texture.isReady = true;
  4572. texture.isCube = true;
  4573. texture.samples = 1;
  4574. texture.generateMipMaps = fullOptions.generateMipMaps;
  4575. texture.samplingMode = fullOptions.samplingMode;
  4576. texture.type = fullOptions.type;
  4577. texture.format = fullOptions.format;
  4578. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4579. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4580. this._internalTexturesCache.push(texture);
  4581. return texture;
  4582. }
  4583. /**
  4584. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4585. * @param rootUrl defines the url where the file to load is located
  4586. * @param scene defines the current scene
  4587. * @param lodScale defines scale to apply to the mip map selection
  4588. * @param lodOffset defines offset to apply to the mip map selection
  4589. * @param onLoad defines an optional callback raised when the texture is loaded
  4590. * @param onError defines an optional callback raised if there is an issue to load the texture
  4591. * @param format defines the format of the data
  4592. * @param forcedExtension defines the extension to use to pick the right loader
  4593. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  4594. * @returns the cube texture as an InternalTexture
  4595. */
  4596. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  4597. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4598. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null,
  4599. createPolynomials: boolean = true): InternalTexture {
  4600. var callback = (loadData: any) => {
  4601. if (!loadData) {
  4602. if (onLoad) {
  4603. onLoad(null);
  4604. }
  4605. return;
  4606. }
  4607. let texture = loadData.texture as InternalTexture;
  4608. if (!createPolynomials) {
  4609. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  4610. }
  4611. else if(loadData.info.sphericalPolynomial){
  4612. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  4613. }
  4614. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4615. if (this._caps.textureLOD) {
  4616. // Do not add extra process if texture lod is supported.
  4617. if (onLoad) {
  4618. onLoad(texture);
  4619. }
  4620. return;
  4621. }
  4622. const mipSlices = 3;
  4623. var gl = this._gl;
  4624. const width = loadData.width;
  4625. if (!width) {
  4626. return;
  4627. }
  4628. const textures: BaseTexture[] = [];
  4629. for (let i = 0; i < mipSlices; i++) {
  4630. //compute LOD from even spacing in smoothness (matching shader calculation)
  4631. let smoothness = i / (mipSlices - 1);
  4632. let roughness = 1 - smoothness;
  4633. let minLODIndex = lodOffset; // roughness = 0
  4634. let maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  4635. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4636. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4637. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4638. glTextureFromLod.type = texture.type;
  4639. glTextureFromLod.format = texture.format;
  4640. glTextureFromLod.width = Math.pow(2, Math.max( Scalar.Log2(width) - mipmapIndex, 0));
  4641. glTextureFromLod.height = glTextureFromLod.width;
  4642. glTextureFromLod.isCube = true;
  4643. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4648. if (loadData.isDDS) {
  4649. var info: DDSInfo = loadData.info;
  4650. var data: any = loadData.data;
  4651. this._unpackFlipY(info.isCompressed);
  4652. DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  4653. }
  4654. else {
  4655. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  4656. }
  4657. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4658. // Wrap in a base texture for easy binding.
  4659. const lodTexture = new BaseTexture(scene);
  4660. lodTexture.isCube = true;
  4661. lodTexture._texture = glTextureFromLod;
  4662. glTextureFromLod.isReady = true;
  4663. textures.push(lodTexture);
  4664. }
  4665. texture._lodTextureHigh = textures[2];
  4666. texture._lodTextureMid = textures[1];
  4667. texture._lodTextureLow = textures[0];
  4668. if (onLoad) {
  4669. onLoad(texture);
  4670. }
  4671. };
  4672. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  4673. }
  4674. /**
  4675. * Creates a cube texture
  4676. * @param rootUrl defines the url where the files to load is located
  4677. * @param scene defines the current scene
  4678. * @param files defines the list of files to load (1 per face)
  4679. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4680. * @param onLoad defines an optional callback raised when the texture is loaded
  4681. * @param onError defines an optional callback raised if there is an issue to load the texture
  4682. * @param format defines the format of the data
  4683. * @param forcedExtension defines the extension to use to pick the right loader
  4684. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4685. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  4686. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  4687. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  4688. * @returns the cube texture as an InternalTexture
  4689. */
  4690. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null): InternalTexture {
  4691. var gl = this._gl;
  4692. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4693. texture.isCube = true;
  4694. texture.url = rootUrl;
  4695. texture.generateMipMaps = !noMipmap;
  4696. texture._lodGenerationScale = lodScale;
  4697. texture._lodGenerationOffset = lodOffset;
  4698. if (!this._doNotHandleContextLost) {
  4699. texture._extension = forcedExtension;
  4700. texture._files = files;
  4701. }
  4702. var lastDot = rootUrl.lastIndexOf('.');
  4703. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4704. let loader: Nullable<IInternalTextureLoader> = null;
  4705. for (let availableLoader of Engine._TextureLoaders) {
  4706. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  4707. loader = availableLoader;
  4708. break;
  4709. }
  4710. }
  4711. let onInternalError = (request?: XMLHttpRequest, exception?: any) => {
  4712. if (loader) {
  4713. const fallbackUrl = loader.getFallbackTextureUrl(rootUrl, this._textureFormatInUse);
  4714. if (fallbackUrl) {
  4715. this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  4716. }
  4717. }
  4718. if (onError && request) {
  4719. onError(request.status + " " + request.statusText, exception);
  4720. }
  4721. }
  4722. if (loader) {
  4723. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  4724. const onloaddata = (data: any) => {
  4725. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4726. loader!.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  4727. };
  4728. if (files && files.length === 6) {
  4729. if (loader.supportCascades) {
  4730. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  4731. }
  4732. else if (onError) {
  4733. onError("Textures type does not support cascades.");
  4734. }
  4735. }
  4736. else {
  4737. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  4738. }
  4739. }
  4740. else {
  4741. if (!files) {
  4742. throw new Error("Cannot load cubemap because files were not defined");
  4743. }
  4744. this._cascadeLoadImgs(rootUrl, scene, imgs => {
  4745. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4746. var height = width;
  4747. this._prepareWorkingCanvas();
  4748. if (!this._workingCanvas || !this._workingContext) {
  4749. return;
  4750. }
  4751. this._workingCanvas.width = width;
  4752. this._workingCanvas.height = height;
  4753. var faces = [
  4754. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4755. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4756. ];
  4757. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4758. this._unpackFlipY(false);
  4759. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4760. for (var index = 0; index < faces.length; index++) {
  4761. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4762. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4763. }
  4764. if (!noMipmap) {
  4765. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4766. }
  4767. this._setCubeMapTextureParams(!noMipmap);
  4768. texture.width = width;
  4769. texture.height = height;
  4770. texture.isReady = true;
  4771. if (format) {
  4772. texture.format = format;
  4773. }
  4774. texture.onLoadedObservable.notifyObservers(texture);
  4775. texture.onLoadedObservable.clear();
  4776. if (onLoad) {
  4777. onLoad();
  4778. }
  4779. }, files, onError);
  4780. }
  4781. this._internalTexturesCache.push(texture);
  4782. return texture;
  4783. }
  4784. /**
  4785. * @hidden
  4786. */
  4787. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  4788. var gl = this._gl;
  4789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4793. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4794. // this.resetTextureCache();
  4795. }
  4796. /**
  4797. * Update a raw cube texture
  4798. * @param texture defines the texture to udpdate
  4799. * @param data defines the data to store
  4800. * @param format defines the data format
  4801. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4802. * @param invertY defines if data must be stored with Y axis inverted
  4803. * @param compression defines the compression used (null by default)
  4804. * @param level defines which level of the texture to update
  4805. */
  4806. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4807. texture._bufferViewArray = data;
  4808. texture.format = format;
  4809. texture.type = type;
  4810. texture.invertY = invertY;
  4811. texture._compression = compression;
  4812. var gl = this._gl;
  4813. var textureType = this._getWebGLTextureType(type);
  4814. var internalFormat = this._getInternalFormat(format);
  4815. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4816. var needConversion = false;
  4817. if (internalFormat === gl.RGB) {
  4818. internalFormat = gl.RGBA;
  4819. needConversion = true;
  4820. }
  4821. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4822. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4823. if (texture.width % 4 !== 0) {
  4824. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4825. }
  4826. // Data are known to be in +X +Y +Z -X -Y -Z
  4827. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4828. let faceData = data[faceIndex];
  4829. if (compression) {
  4830. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4831. } else {
  4832. if (needConversion) {
  4833. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4834. }
  4835. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4836. }
  4837. }
  4838. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4839. if (isPot && texture.generateMipMaps && level === 0) {
  4840. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4841. }
  4842. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4843. // this.resetTextureCache();
  4844. texture.isReady = true;
  4845. }
  4846. /**
  4847. * Creates a new raw cube texture
  4848. * @param data defines the array of data to use to create each face
  4849. * @param size defines the size of the textures
  4850. * @param format defines the format of the data
  4851. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4852. * @param generateMipMaps defines if the engine should generate the mip levels
  4853. * @param invertY defines if data must be stored with Y axis inverted
  4854. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4855. * @param compression defines the compression used (null by default)
  4856. * @returns the cube texture as an InternalTexture
  4857. */
  4858. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4859. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4860. compression: Nullable<string> = null): InternalTexture {
  4861. var gl = this._gl;
  4862. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4863. texture.isCube = true;
  4864. texture.format = format;
  4865. texture.type = type;
  4866. if (!this._doNotHandleContextLost) {
  4867. texture._bufferViewArray = data;
  4868. }
  4869. var textureType = this._getWebGLTextureType(type);
  4870. var internalFormat = this._getInternalFormat(format);
  4871. if (internalFormat === gl.RGB) {
  4872. internalFormat = gl.RGBA;
  4873. }
  4874. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  4875. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4876. generateMipMaps = false;
  4877. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4878. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4879. }
  4880. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4881. generateMipMaps = false;
  4882. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4883. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4884. }
  4885. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  4886. generateMipMaps = false;
  4887. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  4888. }
  4889. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  4890. generateMipMaps = false;
  4891. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  4892. }
  4893. var width = size;
  4894. var height = width;
  4895. texture.width = width;
  4896. texture.height = height;
  4897. // Double check on POT to generate Mips.
  4898. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4899. if (!isPot) {
  4900. generateMipMaps = false;
  4901. }
  4902. // Upload data if needed. The texture won't be ready until then.
  4903. if (data) {
  4904. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4905. }
  4906. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4907. // Filters
  4908. if (data && generateMipMaps) {
  4909. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4910. }
  4911. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4916. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4917. texture.generateMipMaps = generateMipMaps;
  4918. return texture;
  4919. }
  4920. /**
  4921. * Creates a new raw cube texture from a specified url
  4922. * @param url defines the url where the data is located
  4923. * @param scene defines the current scene
  4924. * @param size defines the size of the textures
  4925. * @param format defines the format of the data
  4926. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4927. * @param noMipmap defines if the engine should avoid generating the mip levels
  4928. * @param callback defines a callback used to extract texture data from loaded data
  4929. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  4930. * @param onLoad defines a callback called when texture is loaded
  4931. * @param onError defines a callback called if there is an error
  4932. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4933. * @param invertY defines if data must be stored with Y axis inverted
  4934. * @returns the cube texture as an InternalTexture
  4935. */
  4936. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  4937. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  4938. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  4939. onLoad: Nullable<() => void> = null,
  4940. onError: Nullable<(message?: string, exception?: any) => void> = null,
  4941. samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4942. invertY = false): InternalTexture {
  4943. var gl = this._gl;
  4944. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  4945. scene._addPendingData(texture);
  4946. texture.url = url;
  4947. this._internalTexturesCache.push(texture);
  4948. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  4949. scene._removePendingData(texture);
  4950. if (onError && request) {
  4951. onError(request.status + " " + request.statusText, exception);
  4952. }
  4953. };
  4954. var internalCallback = (data: any) => {
  4955. var width = texture.width;
  4956. var faceDataArrays = callback(data);
  4957. if (!faceDataArrays) {
  4958. return;
  4959. }
  4960. if (mipmapGenerator) {
  4961. var textureType = this._getWebGLTextureType(type);
  4962. var internalFormat = this._getInternalFormat(format);
  4963. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4964. var needConversion = false;
  4965. if (internalFormat === gl.RGB) {
  4966. internalFormat = gl.RGBA;
  4967. needConversion = true;
  4968. }
  4969. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4970. this._unpackFlipY(false);
  4971. var mipData = mipmapGenerator(faceDataArrays);
  4972. for (var level = 0; level < mipData.length; level++) {
  4973. var mipSize = width >> level;
  4974. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  4975. let mipFaceData = mipData[level][faceIndex];
  4976. if (needConversion) {
  4977. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  4978. }
  4979. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  4980. }
  4981. }
  4982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4983. }
  4984. else {
  4985. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  4986. }
  4987. texture.isReady = true;
  4988. // this.resetTextureCache();
  4989. scene._removePendingData(texture);
  4990. if (onLoad) {
  4991. onLoad();
  4992. }
  4993. };
  4994. this._loadFile(url, data => {
  4995. internalCallback(data);
  4996. }, undefined, scene.database, true, onerror);
  4997. return texture;
  4998. };
  4999. /**
  5000. * Update a raw 3D texture
  5001. * @param texture defines the texture to update
  5002. * @param data defines the data to store
  5003. * @param format defines the data format
  5004. * @param invertY defines if data must be stored with Y axis inverted
  5005. * @param compression defines the used compression (can be null)
  5006. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  5007. */
  5008. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  5009. var internalType = this._getWebGLTextureType(textureType);
  5010. var internalFormat = this._getInternalFormat(format);
  5011. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  5012. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5013. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5014. if (!this._doNotHandleContextLost) {
  5015. texture._bufferView = data;
  5016. texture.format = format;
  5017. texture.invertY = invertY;
  5018. texture._compression = compression;
  5019. }
  5020. if (texture.width % 4 !== 0) {
  5021. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  5022. }
  5023. if (compression && data) {
  5024. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  5025. } else {
  5026. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  5027. }
  5028. if (texture.generateMipMaps) {
  5029. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5030. }
  5031. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5032. // this.resetTextureCache();
  5033. texture.isReady = true;
  5034. }
  5035. /**
  5036. * Creates a new raw 3D texture
  5037. * @param data defines the data used to create the texture
  5038. * @param width defines the width of the texture
  5039. * @param height defines the height of the texture
  5040. * @param depth defines the depth of the texture
  5041. * @param format defines the format of the texture
  5042. * @param generateMipMaps defines if the engine must generate mip levels
  5043. * @param invertY defines if data must be stored with Y axis inverted
  5044. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  5045. * @param compression defines the compressed used (can be null)
  5046. * @param textureType defines the compressed used (can be null)
  5047. * @returns a new raw 3D texture (stored in an InternalTexture)
  5048. */
  5049. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  5050. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  5051. texture.baseWidth = width;
  5052. texture.baseHeight = height;
  5053. texture.baseDepth = depth;
  5054. texture.width = width;
  5055. texture.height = height;
  5056. texture.depth = depth;
  5057. texture.format = format;
  5058. texture.type = textureType;
  5059. texture.generateMipMaps = generateMipMaps;
  5060. texture.samplingMode = samplingMode;
  5061. texture.is3D = true;
  5062. if (!this._doNotHandleContextLost) {
  5063. texture._bufferView = data;
  5064. }
  5065. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  5066. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5067. // Filters
  5068. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5069. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5070. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5071. if (generateMipMaps) {
  5072. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5073. }
  5074. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5075. this._internalTexturesCache.push(texture);
  5076. return texture;
  5077. }
  5078. protected _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5079. var gl = this._gl;
  5080. if (!gl) {
  5081. return;
  5082. }
  5083. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  5084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5086. if (!noMipmap && !isCompressed) {
  5087. gl.generateMipmap(gl.TEXTURE_2D);
  5088. }
  5089. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5090. // this.resetTextureCache();
  5091. if (scene) {
  5092. scene._removePendingData(texture);
  5093. }
  5094. texture.onLoadedObservable.notifyObservers(texture);
  5095. texture.onLoadedObservable.clear();
  5096. }
  5097. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5098. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  5099. var maxTextureSize = this.getCaps().maxTextureSize;
  5100. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  5101. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  5102. var gl = this._gl;
  5103. if (!gl) {
  5104. return;
  5105. }
  5106. if (!texture._webGLTexture) {
  5107. // this.resetTextureCache();
  5108. if (scene) {
  5109. scene._removePendingData(texture);
  5110. }
  5111. return;
  5112. }
  5113. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5114. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5115. texture.baseWidth = width;
  5116. texture.baseHeight = height;
  5117. texture.width = potWidth;
  5118. texture.height = potHeight;
  5119. texture.isReady = true;
  5120. if (processFunction(potWidth, potHeight, () => {
  5121. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5122. })) {
  5123. // Returning as texture needs extra async steps
  5124. return;
  5125. }
  5126. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5127. }
  5128. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5129. // Create new RGBA data container.
  5130. var rgbaData: any;
  5131. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5132. rgbaData = new Float32Array(width * height * 4);
  5133. }
  5134. else {
  5135. rgbaData = new Uint32Array(width * height * 4);
  5136. }
  5137. // Convert each pixel.
  5138. for (let x = 0; x < width; x++) {
  5139. for (let y = 0; y < height; y++) {
  5140. let index = (y * width + x) * 3;
  5141. let newIndex = (y * width + x) * 4;
  5142. // Map Old Value to new value.
  5143. rgbaData[newIndex + 0] = rgbData[index + 0];
  5144. rgbaData[newIndex + 1] = rgbData[index + 1];
  5145. rgbaData[newIndex + 2] = rgbData[index + 2];
  5146. // Add fully opaque alpha channel.
  5147. rgbaData[newIndex + 3] = 1;
  5148. }
  5149. }
  5150. return rgbaData;
  5151. }
  5152. /** @hidden */
  5153. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5154. var gl = this._gl;
  5155. if (texture._framebuffer) {
  5156. gl.deleteFramebuffer(texture._framebuffer);
  5157. texture._framebuffer = null;
  5158. }
  5159. if (texture._depthStencilBuffer) {
  5160. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5161. texture._depthStencilBuffer = null;
  5162. }
  5163. if (texture._MSAAFramebuffer) {
  5164. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5165. texture._MSAAFramebuffer = null;
  5166. }
  5167. if (texture._MSAARenderBuffer) {
  5168. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5169. texture._MSAARenderBuffer = null;
  5170. }
  5171. }
  5172. /** @hidden */
  5173. public _releaseTexture(texture: InternalTexture): void {
  5174. this._releaseFramebufferObjects(texture);
  5175. this._deleteTexture(texture._webGLTexture);
  5176. // Unbind channels
  5177. this.unbindAllTextures();
  5178. var index = this._internalTexturesCache.indexOf(texture);
  5179. if (index !== -1) {
  5180. this._internalTexturesCache.splice(index, 1);
  5181. }
  5182. // Integrated fixed lod samplers.
  5183. if (texture._lodTextureHigh) {
  5184. texture._lodTextureHigh.dispose();
  5185. }
  5186. if (texture._lodTextureMid) {
  5187. texture._lodTextureMid.dispose();
  5188. }
  5189. if (texture._lodTextureLow) {
  5190. texture._lodTextureLow.dispose();
  5191. }
  5192. // Set output texture of post process to null if the texture has been released/disposed
  5193. this.scenes.forEach((scene)=>{
  5194. scene.postProcesses.forEach((postProcess)=>{
  5195. if(postProcess._outputTexture == texture){
  5196. postProcess._outputTexture = null;
  5197. }
  5198. });
  5199. scene.cameras.forEach((camera)=>{
  5200. camera._postProcesses.forEach((postProcess)=>{
  5201. if(postProcess){
  5202. if(postProcess._outputTexture == texture){
  5203. postProcess._outputTexture = null;
  5204. }
  5205. }
  5206. });
  5207. });
  5208. })
  5209. }
  5210. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  5211. this._gl.deleteTexture(texture);
  5212. }
  5213. protected setProgram(program: WebGLProgram): void {
  5214. if (this._currentProgram !== program) {
  5215. this._gl.useProgram(program);
  5216. this._currentProgram = program;
  5217. }
  5218. }
  5219. protected _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5220. /**
  5221. * Binds an effect to the webGL context
  5222. * @param effect defines the effect to bind
  5223. */
  5224. public bindSamplers(effect: Effect): void {
  5225. this.setProgram(effect.getProgram());
  5226. var samplers = effect.getSamplers();
  5227. for (var index = 0; index < samplers.length; index++) {
  5228. var uniform = effect.getUniform(samplers[index]);
  5229. if (uniform) {
  5230. this._boundUniforms[index] = uniform;
  5231. }
  5232. }
  5233. this._currentEffect = null;
  5234. }
  5235. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5236. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5237. return;
  5238. }
  5239. // Remove
  5240. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5241. // Bind last to it
  5242. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5243. // Bind to dummy
  5244. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5245. }
  5246. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5247. if (!internalTexture) {
  5248. return -1;
  5249. }
  5250. internalTexture._initialSlot = channel;
  5251. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5252. if (channel !== internalTexture._designatedSlot) {
  5253. this._textureCollisions.addCount(1, false);
  5254. }
  5255. } else {
  5256. if (channel !== internalTexture._designatedSlot) {
  5257. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5258. return internalTexture._designatedSlot;
  5259. } else {
  5260. // No slot for this texture, let's pick a new one (if we find a free slot)
  5261. if (this._nextFreeTextureSlots.length) {
  5262. return this._nextFreeTextureSlots[0];
  5263. }
  5264. // We need to recycle the oldest bound texture, sorry.
  5265. this._textureCollisions.addCount(1, false);
  5266. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5267. }
  5268. }
  5269. }
  5270. return channel;
  5271. }
  5272. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5273. previous!.next = next;
  5274. next!.previous = previous;
  5275. }
  5276. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5277. let currentSlot = internalTexture._designatedSlot;
  5278. if (currentSlot === -1) {
  5279. return -1;
  5280. }
  5281. internalTexture._designatedSlot = -1;
  5282. if (this.disableTextureBindingOptimization) {
  5283. return -1;
  5284. }
  5285. // Remove from bound list
  5286. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5287. // Free the slot
  5288. this._boundTexturesCache[currentSlot] = null;
  5289. this._nextFreeTextureSlots.push(currentSlot);
  5290. return currentSlot;
  5291. }
  5292. private _activateCurrentTexture() {
  5293. if (this._currentTextureChannel !== this._activeChannel) {
  5294. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5295. this._currentTextureChannel = this._activeChannel;
  5296. }
  5297. }
  5298. /** @hidden */
  5299. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  5300. var wasPreviouslyBound = false;
  5301. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5302. this._activeChannel = texture._designatedSlot;
  5303. }
  5304. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5305. let isTextureForRendering = texture && texture._initialSlot > -1;
  5306. if (currentTextureBound !== texture || force) {
  5307. if (currentTextureBound) {
  5308. this._removeDesignatedSlot(currentTextureBound);
  5309. }
  5310. this._activateCurrentTexture();
  5311. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5312. this._boundTexturesCache[this._activeChannel] = texture;
  5313. if (texture) {
  5314. if (!this.disableTextureBindingOptimization) {
  5315. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5316. if (slotIndex > -1) {
  5317. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5318. }
  5319. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5320. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5321. }
  5322. texture._designatedSlot = this._activeChannel;
  5323. }
  5324. } else if (forTextureDataUpdate) {
  5325. wasPreviouslyBound = true;
  5326. this._activateCurrentTexture();
  5327. }
  5328. if (isTextureForRendering && !forTextureDataUpdate) {
  5329. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5330. }
  5331. return wasPreviouslyBound;
  5332. }
  5333. /** @hidden */
  5334. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5335. if (channel < 0) {
  5336. return;
  5337. }
  5338. if (texture) {
  5339. channel = this._getCorrectTextureChannel(channel, texture);
  5340. }
  5341. this._activeChannel = channel;
  5342. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5343. }
  5344. /**
  5345. * Sets a texture to the webGL context from a postprocess
  5346. * @param channel defines the channel to use
  5347. * @param postProcess defines the source postprocess
  5348. */
  5349. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5350. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5351. }
  5352. /**
  5353. * Binds the output of the passed in post process to the texture channel specified
  5354. * @param channel The channel the texture should be bound to
  5355. * @param postProcess The post process which's output should be bound
  5356. */
  5357. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5358. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5359. }
  5360. /**
  5361. * Unbind all textures from the webGL context
  5362. */
  5363. public unbindAllTextures(): void {
  5364. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5365. this._activeChannel = channel;
  5366. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5367. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5368. if (this.webGLVersion > 1) {
  5369. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5370. }
  5371. }
  5372. }
  5373. /**
  5374. * Sets a texture to the according uniform.
  5375. * @param channel The texture channel
  5376. * @param uniform The uniform to set
  5377. * @param texture The texture to apply
  5378. */
  5379. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5380. if (channel < 0) {
  5381. return;
  5382. }
  5383. if (uniform) {
  5384. this._boundUniforms[channel] = uniform;
  5385. }
  5386. this._setTexture(channel, texture);
  5387. }
  5388. /**
  5389. * Sets a depth stencil texture from a render target to the according uniform.
  5390. * @param channel The texture channel
  5391. * @param uniform The uniform to set
  5392. * @param texture The render target texture containing the depth stencil texture to apply
  5393. */
  5394. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5395. if (channel < 0) {
  5396. return;
  5397. }
  5398. if (uniform) {
  5399. this._boundUniforms[channel] = uniform;
  5400. }
  5401. if (!texture || !texture.depthStencilTexture) {
  5402. this._setTexture(channel, null);
  5403. }
  5404. else {
  5405. this._setTexture(channel, texture, false, true);
  5406. }
  5407. }
  5408. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5409. let uniform = this._boundUniforms[sourceSlot];
  5410. if (uniform._currentState === destination) {
  5411. return;
  5412. }
  5413. this._gl.uniform1i(uniform, destination);
  5414. uniform._currentState = destination;
  5415. }
  5416. private _getTextureWrapMode(mode: number): number {
  5417. switch(mode) {
  5418. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  5419. return this._gl.REPEAT;
  5420. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  5421. return this._gl.CLAMP_TO_EDGE;
  5422. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  5423. return this._gl.MIRRORED_REPEAT;
  5424. }
  5425. return this._gl.REPEAT;
  5426. }
  5427. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5428. // Not ready?
  5429. if (!texture) {
  5430. if (this._boundTexturesCache[channel] != null) {
  5431. this._activeChannel = channel;
  5432. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5433. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5434. if (this.webGLVersion > 1) {
  5435. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5436. }
  5437. }
  5438. return false;
  5439. }
  5440. // Video
  5441. if ((<VideoTexture>texture).video) {
  5442. this._activeChannel = channel;
  5443. (<VideoTexture>texture).update();
  5444. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5445. texture.delayLoad();
  5446. return false;
  5447. }
  5448. let internalTexture: InternalTexture;
  5449. if (depthStencilTexture) {
  5450. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5451. }
  5452. else if (texture.isReady()) {
  5453. internalTexture = <InternalTexture>texture.getInternalTexture();
  5454. }
  5455. else if (texture.isCube) {
  5456. internalTexture = this.emptyCubeTexture;
  5457. }
  5458. else if (texture.is3D) {
  5459. internalTexture = this.emptyTexture3D;
  5460. }
  5461. else {
  5462. internalTexture = this.emptyTexture;
  5463. }
  5464. if (!isPartOfTextureArray) {
  5465. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5466. }
  5467. let needToBind = true;
  5468. if (this._boundTexturesCache[channel] === internalTexture) {
  5469. this._moveBoundTextureOnTop(internalTexture);
  5470. if (!isPartOfTextureArray) {
  5471. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5472. }
  5473. needToBind = false;
  5474. }
  5475. this._activeChannel = channel;
  5476. if (internalTexture && internalTexture.is3D) {
  5477. if (needToBind) {
  5478. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5479. }
  5480. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5481. internalTexture._cachedWrapU = texture.wrapU;
  5482. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5483. }
  5484. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5485. internalTexture._cachedWrapV = texture.wrapV;
  5486. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5487. }
  5488. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5489. internalTexture._cachedWrapR = texture.wrapR;
  5490. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5491. }
  5492. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5493. }
  5494. else if (internalTexture && internalTexture.isCube) {
  5495. if (needToBind) {
  5496. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5497. }
  5498. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5499. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5500. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5501. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5502. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5503. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5504. }
  5505. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5506. } else {
  5507. if (needToBind) {
  5508. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5509. }
  5510. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5511. internalTexture._cachedWrapU = texture.wrapU;
  5512. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5513. }
  5514. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5515. internalTexture._cachedWrapV = texture.wrapV;
  5516. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5517. }
  5518. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5519. }
  5520. return true;
  5521. }
  5522. /**
  5523. * Sets an array of texture to the webGL context
  5524. * @param channel defines the channel where the texture array must be set
  5525. * @param uniform defines the associated uniform location
  5526. * @param textures defines the array of textures to bind
  5527. */
  5528. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5529. if (channel < 0 || !uniform) {
  5530. return;
  5531. }
  5532. this._boundUniforms[channel] = uniform;
  5533. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5534. this._textureUnits = new Int32Array(textures.length);
  5535. }
  5536. for (let i = 0; i < textures.length; i++) {
  5537. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5538. }
  5539. this._gl.uniform1iv(uniform, this._textureUnits);
  5540. for (var index = 0; index < textures.length; index++) {
  5541. this._setTexture(this._textureUnits[index], textures[index], true);
  5542. }
  5543. }
  5544. private _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5545. var internalTexture = texture.getInternalTexture();
  5546. if (!internalTexture) {
  5547. return;
  5548. }
  5549. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5550. var value = texture.anisotropicFilteringLevel;
  5551. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  5552. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  5553. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  5554. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5555. }
  5556. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5557. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5558. internalTexture._cachedAnisotropicFilteringLevel = value;
  5559. }
  5560. }
  5561. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5562. this._bindTextureDirectly(target, texture, true, true);
  5563. this._gl.texParameterf(target, parameter, value);
  5564. }
  5565. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5566. if (texture) {
  5567. this._bindTextureDirectly(target, texture, true, true);
  5568. }
  5569. this._gl.texParameteri(target, parameter, value);
  5570. }
  5571. /**
  5572. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5573. * @param x defines the x coordinate of the rectangle where pixels must be read
  5574. * @param y defines the y coordinate of the rectangle where pixels must be read
  5575. * @param width defines the width of the rectangle where pixels must be read
  5576. * @param height defines the height of the rectangle where pixels must be read
  5577. * @returns a Uint8Array containing RGBA colors
  5578. */
  5579. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5580. var data = new Uint8Array(height * width * 4);
  5581. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5582. return data;
  5583. }
  5584. /**
  5585. * Add an externaly attached data from its key.
  5586. * This method call will fail and return false, if such key already exists.
  5587. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5588. * @param key the unique key that identifies the data
  5589. * @param data the data object to associate to the key for this Engine instance
  5590. * @return true if no such key were already present and the data was added successfully, false otherwise
  5591. */
  5592. public addExternalData<T>(key: string, data: T): boolean {
  5593. if (!this._externalData) {
  5594. this._externalData = new StringDictionary<Object>();
  5595. }
  5596. return this._externalData.add(key, data);
  5597. }
  5598. /**
  5599. * Get an externaly attached data from its key
  5600. * @param key the unique key that identifies the data
  5601. * @return the associated data, if present (can be null), or undefined if not present
  5602. */
  5603. public getExternalData<T>(key: string): T {
  5604. if (!this._externalData) {
  5605. this._externalData = new StringDictionary<Object>();
  5606. }
  5607. return <T>this._externalData.get(key);
  5608. }
  5609. /**
  5610. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5611. * @param key the unique key that identifies the data
  5612. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5613. * @return the associated data, can be null if the factory returned null.
  5614. */
  5615. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5616. if (!this._externalData) {
  5617. this._externalData = new StringDictionary<Object>();
  5618. }
  5619. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5620. }
  5621. /**
  5622. * Remove an externaly attached data from the Engine instance
  5623. * @param key the unique key that identifies the data
  5624. * @return true if the data was successfully removed, false if it doesn't exist
  5625. */
  5626. public removeExternalData(key: string): boolean {
  5627. if (!this._externalData) {
  5628. this._externalData = new StringDictionary<Object>();
  5629. }
  5630. return this._externalData.remove(key);
  5631. }
  5632. /**
  5633. * Unbind all vertex attributes from the webGL context
  5634. */
  5635. public unbindAllAttributes() {
  5636. if (this._mustWipeVertexAttributes) {
  5637. this._mustWipeVertexAttributes = false;
  5638. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5639. this._gl.disableVertexAttribArray(i);
  5640. this._vertexAttribArraysEnabled[i] = false;
  5641. this._currentBufferPointers[i].active = false;
  5642. }
  5643. return;
  5644. }
  5645. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5646. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5647. continue;
  5648. }
  5649. this._gl.disableVertexAttribArray(i);
  5650. this._vertexAttribArraysEnabled[i] = false;
  5651. this._currentBufferPointers[i].active = false;
  5652. }
  5653. }
  5654. /**
  5655. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  5656. */
  5657. public releaseEffects() {
  5658. for (var name in this._compiledEffects) {
  5659. this._deleteProgram(this._compiledEffects[name]._program)
  5660. }
  5661. this._compiledEffects = {};
  5662. }
  5663. /**
  5664. * Dispose and release all associated resources
  5665. */
  5666. public dispose(): void {
  5667. this.hideLoadingUI();
  5668. this.stopRenderLoop();
  5669. // Release postProcesses
  5670. while (this.postProcesses.length) {
  5671. this.postProcesses[0].dispose();
  5672. }
  5673. // Empty texture
  5674. if (this._emptyTexture) {
  5675. this._releaseTexture(this._emptyTexture);
  5676. this._emptyTexture = null;
  5677. }
  5678. if (this._emptyCubeTexture) {
  5679. this._releaseTexture(this._emptyCubeTexture);
  5680. this._emptyCubeTexture = null;
  5681. }
  5682. // Rescale PP
  5683. if (this._rescalePostProcess) {
  5684. this._rescalePostProcess.dispose();
  5685. }
  5686. // Release scenes
  5687. while (this.scenes.length) {
  5688. this.scenes[0].dispose();
  5689. }
  5690. // Release audio engine
  5691. if (Engine.audioEngine) {
  5692. Engine.audioEngine.dispose();
  5693. }
  5694. // Release effects
  5695. this.releaseEffects();
  5696. // Unbind
  5697. this.unbindAllAttributes();
  5698. this._boundUniforms = [];
  5699. if (this._dummyFramebuffer) {
  5700. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5701. }
  5702. //WebVR
  5703. this.disableVR();
  5704. // Events
  5705. if (Tools.IsWindowObjectExist()) {
  5706. window.removeEventListener("blur", this._onBlur);
  5707. window.removeEventListener("focus", this._onFocus);
  5708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5710. if (this._renderingCanvas) {
  5711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5714. if (!this._doNotHandleContextLost) {
  5715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5717. }
  5718. }
  5719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5727. if (this._onVrDisplayConnect) {
  5728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5729. if (this._onVrDisplayDisconnect) {
  5730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5731. }
  5732. if (this._onVrDisplayPresentChange) {
  5733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5734. }
  5735. this._onVrDisplayConnect = null;
  5736. this._onVrDisplayDisconnect = null;
  5737. }
  5738. }
  5739. // Remove from Instances
  5740. var index = Engine.Instances.indexOf(this);
  5741. if (index >= 0) {
  5742. Engine.Instances.splice(index, 1);
  5743. }
  5744. this._workingCanvas = null;
  5745. this._workingContext = null;
  5746. this._currentBufferPointers = [];
  5747. this._renderingCanvas = null;
  5748. this._currentProgram = null;
  5749. this._bindedRenderFunction = null;
  5750. this.onResizeObservable.clear();
  5751. this.onCanvasBlurObservable.clear();
  5752. this.onCanvasFocusObservable.clear();
  5753. this.onCanvasPointerOutObservable.clear();
  5754. this.onBeginFrameObservable.clear();
  5755. this.onEndFrameObservable.clear();
  5756. Effect.ResetCache();
  5757. // Abort active requests
  5758. for (let request of this._activeRequests) {
  5759. request.abort();
  5760. }
  5761. }
  5762. // Loading screen
  5763. /**
  5764. * Display the loading screen
  5765. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5766. */
  5767. public displayLoadingUI(): void {
  5768. if (!Tools.IsWindowObjectExist()) {
  5769. return;
  5770. }
  5771. const loadingScreen = this.loadingScreen;
  5772. if (loadingScreen) {
  5773. loadingScreen.displayLoadingUI();
  5774. }
  5775. }
  5776. /**
  5777. * Hide the loading screen
  5778. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5779. */
  5780. public hideLoadingUI(): void {
  5781. if (!Tools.IsWindowObjectExist()) {
  5782. return;
  5783. }
  5784. const loadingScreen = this.loadingScreen;
  5785. if (loadingScreen) {
  5786. loadingScreen.hideLoadingUI();
  5787. }
  5788. }
  5789. /**
  5790. * Gets the current loading screen object
  5791. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5792. */
  5793. public get loadingScreen(): ILoadingScreen {
  5794. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  5795. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  5796. return this._loadingScreen;
  5797. }
  5798. /**
  5799. * Sets the current loading screen object
  5800. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5801. */
  5802. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5803. this._loadingScreen = loadingScreen;
  5804. }
  5805. /**
  5806. * Sets the current loading screen text
  5807. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5808. */
  5809. public set loadingUIText(text: string) {
  5810. this.loadingScreen.loadingUIText = text;
  5811. }
  5812. /**
  5813. * Sets the current loading screen background color
  5814. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5815. */
  5816. public set loadingUIBackgroundColor(color: string) {
  5817. this.loadingScreen.loadingUIBackgroundColor = color;
  5818. }
  5819. /**
  5820. * Attach a new callback raised when context lost event is fired
  5821. * @param callback defines the callback to call
  5822. */
  5823. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5824. if (this._renderingCanvas) {
  5825. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5826. }
  5827. }
  5828. /**
  5829. * Attach a new callback raised when context restored event is fired
  5830. * @param callback defines the callback to call
  5831. */
  5832. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5833. if (this._renderingCanvas) {
  5834. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5835. }
  5836. }
  5837. /**
  5838. * Gets the source code of the vertex shader associated with a specific webGL program
  5839. * @param program defines the program to use
  5840. * @returns a string containing the source code of the vertex shader associated with the program
  5841. */
  5842. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5843. var shaders = this._gl.getAttachedShaders(program);
  5844. if (!shaders) {
  5845. return null;
  5846. }
  5847. return this._gl.getShaderSource(shaders[0]);
  5848. }
  5849. /**
  5850. * Gets the source code of the fragment shader associated with a specific webGL program
  5851. * @param program defines the program to use
  5852. * @returns a string containing the source code of the fragment shader associated with the program
  5853. */
  5854. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5855. var shaders = this._gl.getAttachedShaders(program);
  5856. if (!shaders) {
  5857. return null;
  5858. }
  5859. return this._gl.getShaderSource(shaders[1]);
  5860. }
  5861. /**
  5862. * Get the current error code of the webGL context
  5863. * @returns the error code
  5864. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5865. */
  5866. public getError(): number {
  5867. return this._gl.getError();
  5868. }
  5869. // FPS
  5870. /**
  5871. * Gets the current framerate
  5872. * @returns a number representing the framerate
  5873. */
  5874. public getFps(): number {
  5875. return this._fps;
  5876. }
  5877. /**
  5878. * Gets the time spent between current and previous frame
  5879. * @returns a number representing the delta time in ms
  5880. */
  5881. public getDeltaTime(): number {
  5882. return this._deltaTime;
  5883. }
  5884. private _measureFps(): void {
  5885. this._performanceMonitor.sampleFrame();
  5886. this._fps = this._performanceMonitor.averageFPS;
  5887. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5888. }
  5889. /** @hidden */
  5890. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0): ArrayBufferView {
  5891. let gl = this._gl;
  5892. if (!this._dummyFramebuffer) {
  5893. let dummy = gl.createFramebuffer();
  5894. if (!dummy) {
  5895. throw new Error("Unable to create dummy framebuffer");
  5896. }
  5897. this._dummyFramebuffer = dummy;
  5898. }
  5899. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5900. if (faceIndex > -1) {
  5901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  5902. } else {
  5903. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  5904. }
  5905. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5906. let buffer: ArrayBufferView;
  5907. switch (readType) {
  5908. case gl.UNSIGNED_BYTE:
  5909. buffer = new Uint8Array(4 * width * height);
  5910. readType = gl.UNSIGNED_BYTE;
  5911. break;
  5912. default:
  5913. buffer = new Float32Array(4 * width * height);
  5914. readType = gl.FLOAT;
  5915. break;
  5916. }
  5917. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  5918. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  5919. return buffer;
  5920. }
  5921. private _canRenderToFloatFramebuffer(): boolean {
  5922. if (this._webGLVersion > 1) {
  5923. return this._caps.colorBufferFloat;
  5924. }
  5925. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  5926. }
  5927. private _canRenderToHalfFloatFramebuffer(): boolean {
  5928. if (this._webGLVersion > 1) {
  5929. return this._caps.colorBufferFloat;
  5930. }
  5931. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  5932. }
  5933. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  5934. private _canRenderToFramebuffer(type: number): boolean {
  5935. let gl = this._gl;
  5936. //clear existing errors
  5937. while (gl.getError() !== gl.NO_ERROR) { }
  5938. let successful = true;
  5939. let texture = gl.createTexture();
  5940. gl.bindTexture(gl.TEXTURE_2D, texture);
  5941. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  5942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5943. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5944. let fb = gl.createFramebuffer();
  5945. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  5946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5947. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  5948. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  5949. successful = successful && (gl.getError() === gl.NO_ERROR);
  5950. //try render by clearing frame buffer's color buffer
  5951. if (successful) {
  5952. gl.clear(gl.COLOR_BUFFER_BIT);
  5953. successful = successful && (gl.getError() === gl.NO_ERROR);
  5954. }
  5955. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  5956. if (successful) {
  5957. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  5958. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5959. let readFormat = gl.RGBA;
  5960. let readType = gl.UNSIGNED_BYTE;
  5961. let buffer = new Uint8Array(4);
  5962. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  5963. successful = successful && (gl.getError() === gl.NO_ERROR);
  5964. }
  5965. //clean up
  5966. gl.deleteTexture(texture);
  5967. gl.deleteFramebuffer(fb);
  5968. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5969. //clear accumulated errors
  5970. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  5971. return successful;
  5972. }
  5973. /** @hidden */
  5974. public _getWebGLTextureType(type: number): number {
  5975. if (this._webGLVersion === 1) {
  5976. switch (type) {
  5977. case Engine.TEXTURETYPE_FLOAT:
  5978. return this._gl.FLOAT;
  5979. case Engine.TEXTURETYPE_HALF_FLOAT:
  5980. return this._gl.HALF_FLOAT_OES;
  5981. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  5982. return this._gl.UNSIGNED_BYTE;
  5983. }
  5984. return this._gl.UNSIGNED_BYTE;
  5985. }
  5986. switch (type) {
  5987. case Engine.TEXTURETYPE_BYTE:
  5988. return this._gl.BYTE;
  5989. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  5990. return this._gl.UNSIGNED_BYTE;
  5991. case Engine.TEXTURETYPE_SHORT:
  5992. return this._gl.SHORT;
  5993. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  5994. return this._gl.UNSIGNED_SHORT;
  5995. case Engine.TEXTURETYPE_INT:
  5996. return this._gl.INT;
  5997. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  5998. return this._gl.UNSIGNED_INT;
  5999. case Engine.TEXTURETYPE_FLOAT:
  6000. return this._gl.FLOAT;
  6001. case Engine.TEXTURETYPE_HALF_FLOAT:
  6002. return this._gl.HALF_FLOAT;
  6003. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6004. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  6005. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6006. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  6007. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6008. return this._gl.UNSIGNED_SHORT_5_6_5;
  6009. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6010. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  6011. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  6012. return this._gl.UNSIGNED_INT_24_8;
  6013. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6014. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  6015. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6016. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  6017. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  6018. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  6019. }
  6020. return this._gl.UNSIGNED_BYTE;
  6021. };
  6022. private _getInternalFormat(format: number): number {
  6023. var internalFormat = this._gl.RGBA;
  6024. switch (format) {
  6025. case Engine.TEXTUREFORMAT_ALPHA:
  6026. internalFormat = this._gl.ALPHA;
  6027. break;
  6028. case Engine.TEXTUREFORMAT_LUMINANCE:
  6029. internalFormat = this._gl.LUMINANCE;
  6030. break;
  6031. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6032. internalFormat = this._gl.LUMINANCE_ALPHA;
  6033. break;
  6034. case Engine.TEXTUREFORMAT_RED:
  6035. internalFormat = this._gl.RED;
  6036. break;
  6037. case Engine.TEXTUREFORMAT_RG:
  6038. internalFormat = this._gl.RG;
  6039. break;
  6040. case Engine.TEXTUREFORMAT_RGB:
  6041. internalFormat = this._gl.RGB;
  6042. break;
  6043. case Engine.TEXTUREFORMAT_RGBA:
  6044. internalFormat = this._gl.RGBA;
  6045. break;
  6046. }
  6047. if (this._webGLVersion > 1) {
  6048. switch (format) {
  6049. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6050. internalFormat = this._gl.RED_INTEGER;
  6051. break;
  6052. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6053. internalFormat = this._gl.RG_INTEGER;
  6054. break;
  6055. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6056. internalFormat = this._gl.RGB_INTEGER;
  6057. break;
  6058. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6059. internalFormat = this._gl.RGBA_INTEGER;
  6060. break;
  6061. }
  6062. }
  6063. return internalFormat;
  6064. }
  6065. /** @hidden */
  6066. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  6067. if (this._webGLVersion === 1) {
  6068. if (format !== undefined) {
  6069. switch(format) {
  6070. case Engine.TEXTUREFORMAT_ALPHA:
  6071. return this._gl.ALPHA;
  6072. case Engine.TEXTUREFORMAT_LUMINANCE:
  6073. return this._gl.LUMINANCE;
  6074. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6075. return this._gl.LUMINANCE_ALPHA;
  6076. }
  6077. }
  6078. return this._gl.RGBA;
  6079. }
  6080. switch (type) {
  6081. case Engine.TEXTURETYPE_BYTE:
  6082. switch (format) {
  6083. case Engine.TEXTUREFORMAT_RED:
  6084. return this._gl.R8_SNORM;
  6085. case Engine.TEXTUREFORMAT_RG:
  6086. return this._gl.RG8_SNORM;
  6087. case Engine.TEXTUREFORMAT_RGB:
  6088. return this._gl.RGB8_SNORM;
  6089. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6090. return this._gl.R8I;
  6091. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6092. return this._gl.RG8I;
  6093. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6094. return this._gl.RGB8I;
  6095. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6096. return this._gl.RGBA8I;
  6097. default:
  6098. return this._gl.RGBA8_SNORM;
  6099. }
  6100. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6101. switch (format) {
  6102. case Engine.TEXTUREFORMAT_RED:
  6103. return this._gl.R8;
  6104. case Engine.TEXTUREFORMAT_RG:
  6105. return this._gl.RG8;
  6106. case Engine.TEXTUREFORMAT_RGB:
  6107. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  6108. case Engine.TEXTUREFORMAT_RGBA:
  6109. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  6110. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6111. return this._gl.R8UI;
  6112. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6113. return this._gl.RG8UI;
  6114. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6115. return this._gl.RGB8UI;
  6116. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6117. return this._gl.RGBA8UI;
  6118. default:
  6119. return this._gl.RGBA8;
  6120. }
  6121. case Engine.TEXTURETYPE_SHORT:
  6122. switch (format) {
  6123. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6124. return this._gl.R16I;
  6125. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6126. return this._gl.RG16I;
  6127. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6128. return this._gl.RGB16I;
  6129. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6130. return this._gl.RGBA16I;
  6131. default:
  6132. return this._gl.RGBA16I;
  6133. }
  6134. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6135. switch (format) {
  6136. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6137. return this._gl.R16UI;
  6138. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6139. return this._gl.RG16UI;
  6140. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6141. return this._gl.RGB16UI;
  6142. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6143. return this._gl.RGBA16UI;
  6144. default:
  6145. return this._gl.RGBA16UI;
  6146. }
  6147. case Engine.TEXTURETYPE_INT:
  6148. switch (format) {
  6149. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6150. return this._gl.R32I;
  6151. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6152. return this._gl.RG32I;
  6153. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6154. return this._gl.RGB32I;
  6155. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6156. return this._gl.RGBA32I;
  6157. default:
  6158. return this._gl.RGBA32I;
  6159. }
  6160. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6161. switch (format) {
  6162. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6163. return this._gl.R32UI;
  6164. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6165. return this._gl.RG32UI;
  6166. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6167. return this._gl.RGB32UI;
  6168. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6169. return this._gl.RGBA32UI;
  6170. default:
  6171. return this._gl.RGBA32UI;
  6172. }
  6173. case Engine.TEXTURETYPE_FLOAT:
  6174. switch (format) {
  6175. case Engine.TEXTUREFORMAT_RED:
  6176. return this._gl.R32F; // By default. Other possibility is R16F.
  6177. case Engine.TEXTUREFORMAT_RG:
  6178. return this._gl.RG32F; // By default. Other possibility is RG16F.
  6179. case Engine.TEXTUREFORMAT_RGB:
  6180. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  6181. case Engine.TEXTUREFORMAT_RGBA:
  6182. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  6183. default:
  6184. return this._gl.RGBA32F;
  6185. }
  6186. case Engine.TEXTURETYPE_HALF_FLOAT:
  6187. switch (format) {
  6188. case Engine.TEXTUREFORMAT_RED:
  6189. return this._gl.R16F;
  6190. case Engine.TEXTUREFORMAT_RG:
  6191. return this._gl.RG16F;
  6192. case Engine.TEXTUREFORMAT_RGB:
  6193. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  6194. case Engine.TEXTUREFORMAT_RGBA:
  6195. return this._gl.RGBA16F;
  6196. default:
  6197. return this._gl.RGBA16F;
  6198. }
  6199. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6200. return this._gl.RGB565;
  6201. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6202. return this._gl.R11F_G11F_B10F;
  6203. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6204. return this._gl.RGB9_E5;
  6205. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6206. return this._gl.RGBA4;
  6207. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6208. return this._gl.RGB5_A1;
  6209. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6210. switch (format) {
  6211. case Engine.TEXTUREFORMAT_RGBA:
  6212. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  6213. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6214. return this._gl.RGB10_A2UI;
  6215. default:
  6216. return this._gl.RGB10_A2;
  6217. }
  6218. }
  6219. return this._gl.RGBA8;
  6220. };
  6221. /** @hidden */
  6222. public _getRGBAMultiSampleBufferFormat(type: number): number {
  6223. if (type === Engine.TEXTURETYPE_FLOAT) {
  6224. return this._gl.RGBA32F;
  6225. }
  6226. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6227. return this._gl.RGBA16F;
  6228. }
  6229. return this._gl.RGBA8;
  6230. };
  6231. /** @hidden */
  6232. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6233. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  6234. this._activeRequests.push(request);
  6235. request.onCompleteObservable.add(request => {
  6236. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6237. });
  6238. return request;
  6239. }
  6240. /** @hidden */
  6241. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6242. return new Promise((resolve, reject) => {
  6243. this._loadFile(url, (data) => {
  6244. resolve(data);
  6245. }, undefined, database, useArrayBuffer, (request, exception) => {
  6246. reject(exception);
  6247. })
  6248. });
  6249. }
  6250. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6251. var onload = (data: string | ArrayBuffer) => {
  6252. loadedFiles[index] = data;
  6253. (<any>loadedFiles)._internalCount++;
  6254. if ((<any>loadedFiles)._internalCount === 6) {
  6255. onfinish(loadedFiles);
  6256. }
  6257. };
  6258. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6259. if (onErrorCallBack && request) {
  6260. onErrorCallBack(request.status + " " + request.statusText, exception);
  6261. }
  6262. };
  6263. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6264. }
  6265. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6266. var loadedFiles: (string | ArrayBuffer)[] = [];
  6267. (<any>loadedFiles)._internalCount = 0;
  6268. for (let index = 0; index < 6; index++) {
  6269. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6270. }
  6271. }
  6272. // Statics
  6273. /**
  6274. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6275. * @returns true if the engine can be created
  6276. * @ignorenaming
  6277. */
  6278. public static isSupported(): boolean {
  6279. try {
  6280. var tempcanvas = document.createElement("canvas");
  6281. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6282. return gl != null && !!window.WebGLRenderingContext;
  6283. } catch (e) {
  6284. return false;
  6285. }
  6286. }
  6287. }
  6288. }