babylon.engine.ts 328 KB

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