babylon.engine.ts 313 KB

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