babylon.engine.ts 193 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  12. var magFilter = gl.NEAREST;
  13. var minFilter = gl.NEAREST;
  14. switch (samplingMode) {
  15. case Texture.BILINEAR_SAMPLINGMODE:
  16. magFilter = gl.LINEAR;
  17. if (generateMipMaps) {
  18. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  19. } else {
  20. minFilter = gl.LINEAR;
  21. }
  22. break;
  23. case Texture.TRILINEAR_SAMPLINGMODE:
  24. magFilter = gl.LINEAR;
  25. if (generateMipMaps) {
  26. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  27. } else {
  28. minFilter = gl.LINEAR;
  29. }
  30. break;
  31. case Texture.NEAREST_SAMPLINGMODE:
  32. magFilter = gl.NEAREST;
  33. if (generateMipMaps) {
  34. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  35. } else {
  36. minFilter = gl.NEAREST;
  37. }
  38. break;
  39. case Texture.NEAREST_NEAREST_MIPNEAREST:
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  43. } else {
  44. minFilter = gl.NEAREST;
  45. }
  46. break;
  47. case Texture.NEAREST_LINEAR_MIPNEAREST:
  48. magFilter = gl.NEAREST;
  49. if (generateMipMaps) {
  50. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  51. } else {
  52. minFilter = gl.LINEAR;
  53. }
  54. break;
  55. case Texture.NEAREST_LINEAR_MIPLINEAR:
  56. magFilter = gl.NEAREST;
  57. if (generateMipMaps) {
  58. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  59. } else {
  60. minFilter = gl.LINEAR;
  61. }
  62. break;
  63. case Texture.NEAREST_LINEAR:
  64. magFilter = gl.NEAREST;
  65. minFilter = gl.LINEAR;
  66. break;
  67. case Texture.NEAREST_NEAREST:
  68. magFilter = gl.NEAREST;
  69. minFilter = gl.NEAREST;
  70. break;
  71. case Texture.LINEAR_NEAREST_MIPNEAREST:
  72. magFilter = gl.LINEAR;
  73. if (generateMipMaps) {
  74. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  75. } else {
  76. minFilter = gl.NEAREST;
  77. }
  78. break;
  79. case Texture.LINEAR_NEAREST_MIPLINEAR:
  80. magFilter = gl.LINEAR;
  81. if (generateMipMaps) {
  82. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  83. } else {
  84. minFilter = gl.NEAREST;
  85. }
  86. break;
  87. case Texture.LINEAR_LINEAR:
  88. magFilter = gl.LINEAR;
  89. minFilter = gl.LINEAR;
  90. break;
  91. case Texture.LINEAR_NEAREST:
  92. magFilter = gl.LINEAR;
  93. minFilter = gl.NEAREST;
  94. break;
  95. }
  96. return {
  97. min: minFilter,
  98. mag: magFilter
  99. }
  100. }
  101. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  102. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  103. var img: HTMLImageElement;
  104. var onload = () => {
  105. loadedImages[index] = img;
  106. loadedImages._internalCount++;
  107. if (scene) {
  108. scene._removePendingData(img);
  109. }
  110. if (loadedImages._internalCount === 6) {
  111. onfinish(loadedImages);
  112. }
  113. };
  114. var onerror = () => {
  115. if (scene) {
  116. scene._removePendingData(img);
  117. }
  118. if (onErrorCallBack) {
  119. onErrorCallBack();
  120. }
  121. };
  122. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  123. if (scene) {
  124. scene._addPendingData(img);
  125. }
  126. }
  127. var cascadeLoad = (rootUrl: string, scene,
  128. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  129. var loadedImages: any = [];
  130. loadedImages._internalCount = 0;
  131. for (var index = 0; index < 6; index++) {
  132. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  133. }
  134. };
  135. class BufferPointer {
  136. public active: boolean;
  137. public index: number;
  138. public size: number;
  139. public type: number;
  140. public normalized: boolean;
  141. public stride: number;
  142. public offset: number;
  143. public buffer: WebGLBuffer;
  144. }
  145. export class InstancingAttributeInfo {
  146. /**
  147. * Index/offset of the attribute in the vertex shader
  148. */
  149. index: number;
  150. /**
  151. * size of the attribute, 1, 2, 3 or 4
  152. */
  153. attributeSize: number;
  154. /**
  155. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  156. * default is FLOAT
  157. */
  158. attribyteType: number;
  159. /**
  160. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  161. */
  162. normalized: boolean;
  163. /**
  164. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  165. */
  166. offset: number;
  167. /**
  168. * Name of the GLSL attribute, for debugging purpose only
  169. */
  170. attributeName: string;
  171. }
  172. /**
  173. * Define options used to create a render target texture
  174. */
  175. export class RenderTargetCreationOptions {
  176. generateMipMaps?: boolean;
  177. generateDepthBuffer?: boolean;
  178. generateStencilBuffer?: boolean;
  179. type?: number;
  180. samplingMode?: number;
  181. }
  182. /**
  183. * Regroup several parameters relative to the browser in use
  184. */
  185. export class EngineCapabilities {
  186. /** The maximum textures image */
  187. public maxTexturesImageUnits: number;
  188. public maxVertexTextureImageUnits: number;
  189. /** The maximum texture size */
  190. public maxTextureSize: number;
  191. public maxCubemapTextureSize: number;
  192. public maxRenderTextureSize: number;
  193. public maxVertexAttribs: number;
  194. public maxVaryingVectors: number;
  195. public maxVertexUniformVectors: number;
  196. public maxFragmentUniformVectors: number;
  197. public standardDerivatives: boolean;
  198. public s3tc: WEBGL_compressed_texture_s3tc;
  199. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  200. public etc1: any; //WEBGL_compressed_texture_etc1;
  201. public etc2: any; //WEBGL_compressed_texture_etc;
  202. public astc: any; //WEBGL_compressed_texture_astc;
  203. public textureFloat: boolean;
  204. public vertexArrayObject: boolean;
  205. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  206. public maxAnisotropy: number;
  207. public instancedArrays: boolean;
  208. public uintIndices: boolean;
  209. public highPrecisionShaderSupported: boolean;
  210. public fragmentDepthSupported: boolean;
  211. public textureFloatLinearFiltering: boolean;
  212. public textureFloatRender: boolean;
  213. public textureHalfFloat: boolean;
  214. public textureHalfFloatLinearFiltering: boolean;
  215. public textureHalfFloatRender: boolean;
  216. public textureLOD: boolean;
  217. public drawBuffersExtension: boolean;
  218. public depthTextureExtension: boolean;
  219. public colorBufferFloat: boolean;
  220. }
  221. export interface EngineOptions extends WebGLContextAttributes {
  222. limitDeviceRatio?: number;
  223. autoEnableWebVR?: boolean;
  224. disableWebGL2Support?: boolean;
  225. audioEngine?: boolean;
  226. deterministicLockstep?: boolean;
  227. lockstepMaxSteps?: number;
  228. doNotHandleContextLost?: boolean;
  229. }
  230. /**
  231. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  232. */
  233. export class Engine {
  234. public static Instances = new Array<Engine>();
  235. public static get LastCreatedEngine(): Engine {
  236. if (Engine.Instances.length === 0) {
  237. return null;
  238. }
  239. return Engine.Instances[Engine.Instances.length - 1];
  240. }
  241. public static get LastCreatedScene(): Scene {
  242. var lastCreatedEngine = Engine.LastCreatedEngine;
  243. if (!lastCreatedEngine) {
  244. return null;
  245. }
  246. if (lastCreatedEngine.scenes.length === 0) {
  247. return null;
  248. }
  249. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  250. }
  251. /**
  252. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  253. */
  254. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  255. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  256. var engine = Engine.Instances[engineIndex];
  257. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  258. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  259. }
  260. }
  261. }
  262. // Const statics
  263. private static _ALPHA_DISABLE = 0;
  264. private static _ALPHA_ADD = 1;
  265. private static _ALPHA_COMBINE = 2;
  266. private static _ALPHA_SUBTRACT = 3;
  267. private static _ALPHA_MULTIPLY = 4;
  268. private static _ALPHA_MAXIMIZED = 5;
  269. private static _ALPHA_ONEONE = 6;
  270. private static _ALPHA_PREMULTIPLIED = 7;
  271. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  272. private static _ALPHA_INTERPOLATE = 9;
  273. private static _ALPHA_SCREENMODE = 10;
  274. private static _DELAYLOADSTATE_NONE = 0;
  275. private static _DELAYLOADSTATE_LOADED = 1;
  276. private static _DELAYLOADSTATE_LOADING = 2;
  277. private static _DELAYLOADSTATE_NOTLOADED = 4;
  278. private static _TEXTUREFORMAT_ALPHA = 0;
  279. private static _TEXTUREFORMAT_LUMINANCE = 1;
  280. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  281. private static _TEXTUREFORMAT_RGB = 4;
  282. private static _TEXTUREFORMAT_RGBA = 5;
  283. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  284. private static _TEXTURETYPE_FLOAT = 1;
  285. private static _TEXTURETYPE_HALF_FLOAT = 2;
  286. // Depht or Stencil test Constants.
  287. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  288. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  289. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  290. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  291. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  292. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  293. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  294. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  295. public static get NEVER(): number {
  296. return Engine._NEVER;
  297. }
  298. public static get ALWAYS(): number {
  299. return Engine._ALWAYS;
  300. }
  301. public static get LESS(): number {
  302. return Engine._LESS;
  303. }
  304. public static get EQUAL(): number {
  305. return Engine._EQUAL;
  306. }
  307. public static get LEQUAL(): number {
  308. return Engine._LEQUAL;
  309. }
  310. public static get GREATER(): number {
  311. return Engine._GREATER;
  312. }
  313. public static get GEQUAL(): number {
  314. return Engine._GEQUAL;
  315. }
  316. public static get NOTEQUAL(): number {
  317. return Engine._NOTEQUAL;
  318. }
  319. // Stencil Actions Constants.
  320. private static _KEEP = 0x1E00;
  321. private static _REPLACE = 0x1E01;
  322. private static _INCR = 0x1E02;
  323. private static _DECR = 0x1E03;
  324. private static _INVERT = 0x150A;
  325. private static _INCR_WRAP = 0x8507;
  326. private static _DECR_WRAP = 0x8508;
  327. public static get KEEP(): number {
  328. return Engine._KEEP;
  329. }
  330. public static get REPLACE(): number {
  331. return Engine._REPLACE;
  332. }
  333. public static get INCR(): number {
  334. return Engine._INCR;
  335. }
  336. public static get DECR(): number {
  337. return Engine._DECR;
  338. }
  339. public static get INVERT(): number {
  340. return Engine._INVERT;
  341. }
  342. public static get INCR_WRAP(): number {
  343. return Engine._INCR_WRAP;
  344. }
  345. public static get DECR_WRAP(): number {
  346. return Engine._DECR_WRAP;
  347. }
  348. public static get ALPHA_DISABLE(): number {
  349. return Engine._ALPHA_DISABLE;
  350. }
  351. public static get ALPHA_ONEONE(): number {
  352. return Engine._ALPHA_ONEONE;
  353. }
  354. public static get ALPHA_ADD(): number {
  355. return Engine._ALPHA_ADD;
  356. }
  357. public static get ALPHA_COMBINE(): number {
  358. return Engine._ALPHA_COMBINE;
  359. }
  360. public static get ALPHA_SUBTRACT(): number {
  361. return Engine._ALPHA_SUBTRACT;
  362. }
  363. public static get ALPHA_MULTIPLY(): number {
  364. return Engine._ALPHA_MULTIPLY;
  365. }
  366. public static get ALPHA_MAXIMIZED(): number {
  367. return Engine._ALPHA_MAXIMIZED;
  368. }
  369. public static get ALPHA_PREMULTIPLIED(): number {
  370. return Engine._ALPHA_PREMULTIPLIED;
  371. }
  372. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  373. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  374. }
  375. public static get ALPHA_INTERPOLATE(): number {
  376. return Engine._ALPHA_INTERPOLATE;
  377. }
  378. public static get ALPHA_SCREENMODE(): number {
  379. return Engine._ALPHA_SCREENMODE;
  380. }
  381. public static get DELAYLOADSTATE_NONE(): number {
  382. return Engine._DELAYLOADSTATE_NONE;
  383. }
  384. public static get DELAYLOADSTATE_LOADED(): number {
  385. return Engine._DELAYLOADSTATE_LOADED;
  386. }
  387. public static get DELAYLOADSTATE_LOADING(): number {
  388. return Engine._DELAYLOADSTATE_LOADING;
  389. }
  390. public static get DELAYLOADSTATE_NOTLOADED(): number {
  391. return Engine._DELAYLOADSTATE_NOTLOADED;
  392. }
  393. public static get TEXTUREFORMAT_ALPHA(): number {
  394. return Engine._TEXTUREFORMAT_ALPHA;
  395. }
  396. public static get TEXTUREFORMAT_LUMINANCE(): number {
  397. return Engine._TEXTUREFORMAT_LUMINANCE;
  398. }
  399. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  400. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  401. }
  402. public static get TEXTUREFORMAT_RGB(): number {
  403. return Engine._TEXTUREFORMAT_RGB;
  404. }
  405. public static get TEXTUREFORMAT_RGBA(): number {
  406. return Engine._TEXTUREFORMAT_RGBA;
  407. }
  408. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  409. return Engine._TEXTURETYPE_UNSIGNED_INT;
  410. }
  411. public static get TEXTURETYPE_FLOAT(): number {
  412. return Engine._TEXTURETYPE_FLOAT;
  413. }
  414. public static get TEXTURETYPE_HALF_FLOAT(): number {
  415. return Engine._TEXTURETYPE_HALF_FLOAT;
  416. }
  417. // Texture rescaling mode
  418. private static _SCALEMODE_FLOOR = 1;
  419. private static _SCALEMODE_NEAREST = 2;
  420. private static _SCALEMODE_CEILING = 3;
  421. public static get SCALEMODE_FLOOR(): number {
  422. return Engine._SCALEMODE_FLOOR;
  423. }
  424. public static get SCALEMODE_NEAREST(): number {
  425. return Engine._SCALEMODE_NEAREST;
  426. }
  427. public static get SCALEMODE_CEILING(): number {
  428. return Engine._SCALEMODE_CEILING;
  429. }
  430. public static get Version(): string {
  431. return "3.1-alpha";
  432. }
  433. // Updatable statics so stick with vars here
  434. public static CollisionsEpsilon = 0.001;
  435. public static CodeRepository = "src/";
  436. public static ShadersRepository = "src/Shaders/";
  437. // Public members
  438. public forcePOTTextures = false;
  439. public isFullscreen = false;
  440. public isPointerLock = false;
  441. public cullBackFaces = true;
  442. public renderEvenInBackground = true;
  443. public preventCacheWipeBetweenFrames = false;
  444. // To enable/disable IDB support and avoid XHR on .manifest
  445. public enableOfflineSupport = false;
  446. public scenes = new Array<Scene>();
  447. public postProcesses = new Array<PostProcess>();
  448. // Observables
  449. /**
  450. * Observable event triggered each time the rendering canvas is resized
  451. */
  452. public onResizeObservable = new Observable<Engine>();
  453. /**
  454. * Observable event triggered each time the canvas loses focus
  455. */
  456. public onCanvasBlurObservable = new Observable<Engine>();
  457. /**
  458. * Observable event triggered each time the canvas gains focus
  459. */
  460. public onCanvasFocusObservable = new Observable<Engine>();
  461. /**
  462. * Observable event triggered each time the canvas receives pointerout event
  463. */
  464. public onCanvasPointerOutObservable = new Observable<Engine>();
  465. //WebVR
  466. private _vrDisplays: any[];
  467. private _vrDisplayEnabled;
  468. private _oldSize: BABYLON.Size;
  469. private _oldHardwareScaleFactor: number;
  470. private _vrExclusivePointerMode = false;
  471. public get isInVRExclusivePointerMode(): boolean {
  472. return this._vrExclusivePointerMode;
  473. }
  474. // Uniform buffers list
  475. public disableUniformBuffers = false;
  476. public _uniformBuffers = new Array<UniformBuffer>();
  477. public get supportsUniformBuffers(): boolean {
  478. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  479. }
  480. // Private Members
  481. private _gl: WebGLRenderingContext;
  482. private _renderingCanvas: HTMLCanvasElement;
  483. private _windowIsBackground = false;
  484. private _webGLVersion = 1.0;
  485. public get needPOTTextures(): boolean {
  486. return this._webGLVersion < 2 || this.forcePOTTextures;
  487. }
  488. private _badOS = false;
  489. public get badOS(): boolean {
  490. return this._badOS;
  491. }
  492. private _badDesktopOS = false;
  493. public get badDesktopOS(): boolean {
  494. return this._badDesktopOS;
  495. }
  496. public static audioEngine: AudioEngine;
  497. // Focus
  498. private _onFocus: () => void;
  499. private _onBlur: () => void;
  500. private _onCanvasPointerOut: () => void;
  501. private _onCanvasBlur: () => void;
  502. private _onCanvasFocus: () => void;
  503. private _onFullscreenChange: () => void;
  504. private _onPointerLockChange: () => void;
  505. private _onVRDisplayPointerRestricted: () => void;
  506. private _onVRDisplayPointerUnrestricted: () => void;
  507. // VRDisplay connection
  508. private _onVrDisplayConnect: (display: any) => void;
  509. private _onVrDisplayDisconnect: () => void;
  510. public onVRDisplayChangedObservable = new Observable<any>();
  511. private _hardwareScalingLevel: number;
  512. private _caps: EngineCapabilities;
  513. private _pointerLockRequested: boolean;
  514. private _alphaTest: boolean;
  515. private _isStencilEnable: boolean;
  516. private _colorWrite = true;
  517. private _loadingScreen: ILoadingScreen;
  518. public _drawCalls = new PerfCounter();
  519. private _glVersion: string;
  520. private _glRenderer: string;
  521. private _glVendor: string;
  522. private _videoTextureSupported: boolean;
  523. private _renderingQueueLaunched = false;
  524. private _activeRenderLoops = [];
  525. // Deterministic lockstepMaxSteps
  526. private _deterministicLockstep: boolean = false;
  527. private _lockstepMaxSteps: number = 4;
  528. // Lost context
  529. public onContextLostObservable = new Observable<Engine>();
  530. public onContextRestoredObservable = new Observable<Engine>();
  531. private _onContextLost: (evt: Event) => void;
  532. private _onContextRestored: (evt: Event) => void;
  533. private _contextWasLost = false;
  534. private _doNotHandleContextLost = false;
  535. // FPS
  536. private _performanceMonitor = new PerformanceMonitor();
  537. private _fps = 60;
  538. private _deltaTime = 0;
  539. /**
  540. * Turn this value on if you want to pause FPS computation when in background
  541. */
  542. public disablePerformanceMonitorInBackground = false;
  543. public get performanceMonitor(): PerformanceMonitor {
  544. return this._performanceMonitor;
  545. }
  546. // States
  547. private _depthCullingState = new Internals._DepthCullingState();
  548. private _stencilState = new Internals._StencilState();
  549. private _alphaState = new Internals._AlphaState();
  550. private _alphaMode = Engine.ALPHA_DISABLE;
  551. // Cache
  552. private _internalTexturesCache = new Array<InternalTexture>();
  553. private _maxTextureChannels = 16;
  554. private _activeTexture: number;
  555. private _activeTexturesCache: { [key: string]: WebGLTexture } = {};
  556. private _currentEffect: Effect;
  557. private _currentProgram: WebGLProgram;
  558. private _compiledEffects = {};
  559. private _vertexAttribArraysEnabled: boolean[] = [];
  560. private _cachedViewport: Viewport;
  561. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  562. private _cachedVertexBuffers: any;
  563. private _cachedIndexBuffer: WebGLBuffer;
  564. private _cachedEffectForVertexBuffers: Effect;
  565. private _currentRenderTarget: InternalTexture;
  566. private _uintIndicesCurrentlySet = false;
  567. private _currentBoundBuffer = new Array<WebGLBuffer>();
  568. private _currentFramebuffer: WebGLFramebuffer;
  569. private _currentBufferPointers = new Array<BufferPointer>();
  570. private _currentInstanceLocations = new Array<number>();
  571. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  572. private _textureUnits: Int32Array;
  573. private _workingCanvas: HTMLCanvasElement;
  574. private _workingContext: CanvasRenderingContext2D;
  575. private _rescalePostProcess: PassPostProcess;
  576. private _dummyFramebuffer: WebGLFramebuffer;
  577. private _externalData: StringDictionary<Object>;
  578. private _bindedRenderFunction: any;
  579. private _vaoRecordInProgress = false;
  580. private _mustWipeVertexAttributes = false;
  581. private _emptyTexture: InternalTexture;
  582. private _emptyCubeTexture: InternalTexture;
  583. private _frameHandler: number;
  584. // Hardware supported Compressed Textures
  585. private _texturesSupported = new Array<string>();
  586. private _textureFormatInUse: string;
  587. public get texturesSupported(): Array<string> {
  588. return this._texturesSupported;
  589. }
  590. public get textureFormatInUse(): string {
  591. return this._textureFormatInUse;
  592. }
  593. public get currentViewport(): Viewport {
  594. return this._cachedViewport;
  595. }
  596. // Empty texture
  597. public get emptyTexture(): InternalTexture {
  598. if (!this._emptyTexture) {
  599. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  600. }
  601. return this._emptyTexture;
  602. }
  603. public get emptyCubeTexture(): InternalTexture {
  604. if (!this._emptyCubeTexture) {
  605. var faceData = new Uint8Array(4);
  606. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  607. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  608. }
  609. return this._emptyCubeTexture;
  610. }
  611. /**
  612. * @constructor
  613. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  614. * @param {boolean} [antialias] - enable antialias
  615. * @param options - further options to be sent to the getContext function
  616. */
  617. constructor(canvasOrContext: HTMLCanvasElement | WebGLRenderingContext, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  618. var canvas: HTMLCanvasElement;
  619. Engine.Instances.push(this);
  620. options = options || {};
  621. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  622. canvas = <HTMLCanvasElement>canvasOrContext;
  623. this._renderingCanvas = canvas;
  624. if (antialias != null) {
  625. options.antialias = antialias;
  626. }
  627. if (options.deterministicLockstep === undefined) {
  628. options.deterministicLockstep = false;
  629. }
  630. if (options.lockstepMaxSteps === undefined) {
  631. options.lockstepMaxSteps = 4;
  632. }
  633. if (options.preserveDrawingBuffer === undefined) {
  634. options.preserveDrawingBuffer = false;
  635. }
  636. if (options.audioEngine === undefined) {
  637. options.audioEngine = true;
  638. }
  639. if (options.stencil === undefined) {
  640. options.stencil = true;
  641. }
  642. this._deterministicLockstep = options.deterministicLockstep;
  643. this._lockstepMaxSteps = options.lockstepMaxSteps;
  644. this._doNotHandleContextLost = options.doNotHandleContextLost;
  645. // GL
  646. if (!options.disableWebGL2Support) {
  647. try {
  648. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  649. if (this._gl) {
  650. this._webGLVersion = 2.0;
  651. }
  652. } catch (e) {
  653. // Do nothing
  654. }
  655. }
  656. if (!this._gl) {
  657. if (!canvas) {
  658. throw new Error("The provided canvas is null or undefined.");
  659. }
  660. try {
  661. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  662. } catch (e) {
  663. throw new Error("WebGL not supported");
  664. }
  665. }
  666. if (!this._gl) {
  667. throw new Error("WebGL not supported");
  668. }
  669. this._onCanvasFocus = () => {
  670. this.onCanvasFocusObservable.notifyObservers(this);
  671. }
  672. this._onCanvasBlur = () => {
  673. this.onCanvasBlurObservable.notifyObservers(this);
  674. }
  675. canvas.addEventListener("focus", this._onCanvasFocus);
  676. canvas.addEventListener("blur", this._onCanvasBlur);
  677. this._onBlur = () => {
  678. if (this.disablePerformanceMonitorInBackground) {
  679. this._performanceMonitor.disable();
  680. }
  681. this._windowIsBackground = true;
  682. };
  683. this._onFocus = () => {
  684. if (this.disablePerformanceMonitorInBackground) {
  685. this._performanceMonitor.enable();
  686. }
  687. this._windowIsBackground = false;
  688. };
  689. this._onCanvasPointerOut = () => {
  690. this.onCanvasPointerOutObservable.notifyObservers(this);
  691. };
  692. window.addEventListener("blur", this._onBlur);
  693. window.addEventListener("focus", this._onFocus);
  694. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  695. // Context lost
  696. if (!this._doNotHandleContextLost) {
  697. this._onContextLost = (evt: Event) => {
  698. evt.preventDefault();
  699. this._contextWasLost = true;
  700. Tools.Warn("WebGL context lost.");
  701. this.onContextLostObservable.notifyObservers(this);
  702. };
  703. this._onContextRestored = (evt: Event) => {
  704. // Adding a timeout to avoid race condition at browser level
  705. setTimeout(()=> {
  706. // Rebuild gl context
  707. this._initGLContext();
  708. // Rebuild effects
  709. this._rebuildEffects();
  710. // Rebuild textures
  711. this._rebuildInternalTextures();
  712. // Rebuild buffers
  713. this._rebuildBuffers();
  714. // Cache
  715. this.wipeCaches(true);
  716. Tools.Warn("WebGL context successfully restored.");
  717. this.onContextRestoredObservable.notifyObservers(this);
  718. this._contextWasLost = false;
  719. }, 0);
  720. };
  721. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  722. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  723. }
  724. } else {
  725. this._gl = <WebGLRenderingContext>canvasOrContext;
  726. this._renderingCanvas = this._gl.canvas
  727. if (this._gl.renderbufferStorageMultisample) {
  728. this._webGLVersion = 2.0;
  729. }
  730. options.stencil = this._gl.getContextAttributes().stencil;
  731. }
  732. // Viewport
  733. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  734. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  735. this.resize();
  736. this._isStencilEnable = options.stencil;
  737. this._initGLContext();
  738. if (canvas) {
  739. // Fullscreen
  740. this._onFullscreenChange = () => {
  741. if (document.fullscreen !== undefined) {
  742. this.isFullscreen = document.fullscreen;
  743. } else if (document.mozFullScreen !== undefined) {
  744. this.isFullscreen = document.mozFullScreen;
  745. } else if (document.webkitIsFullScreen !== undefined) {
  746. this.isFullscreen = document.webkitIsFullScreen;
  747. } else if (document.msIsFullScreen !== undefined) {
  748. this.isFullscreen = document.msIsFullScreen;
  749. }
  750. // Pointer lock
  751. if (this.isFullscreen && this._pointerLockRequested) {
  752. canvas.requestPointerLock = canvas.requestPointerLock ||
  753. canvas.msRequestPointerLock ||
  754. canvas.mozRequestPointerLock ||
  755. canvas.webkitRequestPointerLock;
  756. if (canvas.requestPointerLock) {
  757. canvas.requestPointerLock();
  758. }
  759. }
  760. };
  761. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  762. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  763. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  764. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  765. // Pointer lock
  766. this._onPointerLockChange = () => {
  767. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  768. document.webkitPointerLockElement === canvas ||
  769. document.msPointerLockElement === canvas ||
  770. document.pointerLockElement === canvas
  771. );
  772. };
  773. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  774. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  775. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  776. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  777. this._onVRDisplayPointerRestricted = () => {
  778. this._vrExclusivePointerMode = true;
  779. canvas.requestPointerLock();
  780. }
  781. this._onVRDisplayPointerUnrestricted = () => {
  782. this._vrExclusivePointerMode = false;
  783. document.exitPointerLock();
  784. }
  785. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  786. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  787. }
  788. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  789. Engine.audioEngine = new AudioEngine();
  790. }
  791. // Prepare buffer pointers
  792. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  793. this._currentBufferPointers[i] = new BufferPointer();
  794. }
  795. // Load WebVR Devices
  796. if (options.autoEnableWebVR) {
  797. this.initWebVR();
  798. }
  799. // Detect if we are running on a faulty buggy OS.
  800. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  801. // Detect if we are running on a faulty buggy desktop OS.
  802. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  803. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  804. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  805. }
  806. private _rebuildInternalTextures(): void {
  807. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  808. for (var internalTexture of currentState) {
  809. internalTexture._rebuild();
  810. }
  811. }
  812. private _rebuildEffects(): void {
  813. for (var key in this._compiledEffects) {
  814. let effect = <Effect>this._compiledEffects[key];
  815. effect._prepareEffect();
  816. }
  817. Effect.ResetCache();
  818. }
  819. private _rebuildBuffers(): void {
  820. // Index / Vertex
  821. for (var scene of this.scenes) {
  822. scene.resetCachedMaterial();
  823. scene._rebuildGeometries();
  824. scene._rebuildTextures();
  825. }
  826. // Uniforms
  827. for (var uniformBuffer of this._uniformBuffers) {
  828. uniformBuffer._rebuild();
  829. }
  830. }
  831. private _initGLContext(): void {
  832. // Caps
  833. this._caps = new EngineCapabilities();
  834. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  835. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  836. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  837. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  838. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  839. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  840. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  841. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  842. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  843. // Infos
  844. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  845. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  846. if (rendererInfo != null) {
  847. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  848. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  849. }
  850. if (!this._glVendor) {
  851. this._glVendor = "Unknown vendor";
  852. }
  853. if (!this._glRenderer) {
  854. this._glRenderer = "Unknown renderer";
  855. }
  856. // Constants
  857. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  858. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  859. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  860. this._gl.DEPTH24_STENCIL8 = 35056;
  861. // Extensions
  862. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  863. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  864. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  865. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  866. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  867. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  868. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  869. 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');
  870. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  871. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  872. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  873. this._caps.highPrecisionShaderSupported = true;
  874. // Checks if some of the format renders first to allow the use of webgl inspector.
  875. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  876. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  877. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  878. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  879. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  880. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  881. if (this._webGLVersion > 1) {
  882. this._gl.HALF_FLOAT_OES = 0x140B;
  883. }
  884. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  885. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  886. // Draw buffers
  887. if (this._webGLVersion > 1) {
  888. this._caps.drawBuffersExtension = true;
  889. } else {
  890. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  891. if (drawBuffersExtension !== null) {
  892. this._caps.drawBuffersExtension = true;
  893. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  894. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  895. for (var i = 0; i < 16; i++) {
  896. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  897. }
  898. } else {
  899. this._caps.drawBuffersExtension = false;
  900. }
  901. }
  902. // Depth Texture
  903. if (this._webGLVersion > 1) {
  904. this._caps.depthTextureExtension = true;
  905. } else {
  906. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  907. if (depthTextureExtension != null) {
  908. this._caps.depthTextureExtension = true;
  909. }
  910. }
  911. // Vertex array object
  912. if (this._webGLVersion > 1) {
  913. this._caps.vertexArrayObject = true;
  914. } else {
  915. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  916. if (vertexArrayObjectExtension != null) {
  917. this._caps.vertexArrayObject = true;
  918. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  919. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  920. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  921. } else {
  922. this._caps.vertexArrayObject = false;
  923. }
  924. }
  925. // Instances count
  926. if (this._webGLVersion > 1) {
  927. this._caps.instancedArrays = true;
  928. } else {
  929. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  930. if (instanceExtension != null) {
  931. this._caps.instancedArrays = true;
  932. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  933. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  934. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  935. } else {
  936. this._caps.instancedArrays = false;
  937. }
  938. }
  939. // Intelligently add supported compressed formats in order to check for.
  940. // Check for ASTC support first as it is most powerful and to be very cross platform.
  941. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  942. // Likely no hardware which supports both PVR & DXT, so order matters little.
  943. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  944. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  945. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  946. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  947. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  948. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  949. if (this._gl.getShaderPrecisionFormat) {
  950. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  951. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  952. }
  953. // Depth buffer
  954. this.setDepthBuffer(true);
  955. this.setDepthFunctionToLessOrEqual();
  956. this.setDepthWrite(true);
  957. }
  958. public get webGLVersion(): number {
  959. return this._webGLVersion;
  960. }
  961. /**
  962. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  963. */
  964. public get isStencilEnable(): boolean {
  965. return this._isStencilEnable;
  966. }
  967. private _prepareWorkingCanvas(): void {
  968. if (this._workingCanvas) {
  969. return;
  970. }
  971. this._workingCanvas = document.createElement("canvas");
  972. this._workingContext = this._workingCanvas.getContext("2d");
  973. }
  974. public resetTextureCache() {
  975. for (var key in this._activeTexturesCache) {
  976. this._activeTexturesCache[key] = null;
  977. }
  978. }
  979. public isDeterministicLockStep(): boolean {
  980. return this._deterministicLockstep;
  981. }
  982. public getLockstepMaxSteps(): number {
  983. return this._lockstepMaxSteps;
  984. }
  985. public getGlInfo() {
  986. return {
  987. vendor: this._glVendor,
  988. renderer: this._glRenderer,
  989. version: this._glVersion
  990. }
  991. }
  992. public getAspectRatio(camera: Camera, useScreen = false): number {
  993. var viewport = camera.viewport;
  994. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  995. }
  996. public getRenderWidth(useScreen = false): number {
  997. if (!useScreen && this._currentRenderTarget) {
  998. return this._currentRenderTarget.width;
  999. }
  1000. return this._gl.drawingBufferWidth;
  1001. }
  1002. public getRenderHeight(useScreen = false): number {
  1003. if (!useScreen && this._currentRenderTarget) {
  1004. return this._currentRenderTarget.height;
  1005. }
  1006. return this._gl.drawingBufferHeight;
  1007. }
  1008. public getRenderingCanvas(): HTMLCanvasElement {
  1009. return this._renderingCanvas;
  1010. }
  1011. public getRenderingCanvasClientRect(): ClientRect {
  1012. return this._renderingCanvas.getBoundingClientRect();
  1013. }
  1014. public setHardwareScalingLevel(level: number): void {
  1015. this._hardwareScalingLevel = level;
  1016. this.resize();
  1017. }
  1018. public getHardwareScalingLevel(): number {
  1019. return this._hardwareScalingLevel;
  1020. }
  1021. public getLoadedTexturesCache(): InternalTexture[] {
  1022. return this._internalTexturesCache;
  1023. }
  1024. public getCaps(): EngineCapabilities {
  1025. return this._caps;
  1026. }
  1027. /** The number of draw calls submitted last frame */
  1028. public get drawCalls(): number {
  1029. return this._drawCalls.current;
  1030. }
  1031. public get drawCallsPerfCounter(): PerfCounter {
  1032. return this._drawCalls;
  1033. }
  1034. public getDepthFunction(): number {
  1035. return this._depthCullingState.depthFunc;
  1036. }
  1037. public setDepthFunction(depthFunc: number) {
  1038. this._depthCullingState.depthFunc = depthFunc;
  1039. }
  1040. public setDepthFunctionToGreater(): void {
  1041. this._depthCullingState.depthFunc = this._gl.GREATER;
  1042. }
  1043. public setDepthFunctionToGreaterOrEqual(): void {
  1044. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1045. }
  1046. public setDepthFunctionToLess(): void {
  1047. this._depthCullingState.depthFunc = this._gl.LESS;
  1048. }
  1049. public setDepthFunctionToLessOrEqual(): void {
  1050. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1051. }
  1052. public getStencilBuffer(): boolean {
  1053. return this._stencilState.stencilTest;
  1054. }
  1055. public setStencilBuffer(enable: boolean): void {
  1056. this._stencilState.stencilTest = enable;
  1057. }
  1058. public getStencilMask(): number {
  1059. return this._stencilState.stencilMask;
  1060. }
  1061. public setStencilMask(mask: number): void {
  1062. this._stencilState.stencilMask = mask;
  1063. }
  1064. public getStencilFunction(): number {
  1065. return this._stencilState.stencilFunc;
  1066. }
  1067. public getStencilFunctionReference(): number {
  1068. return this._stencilState.stencilFuncRef;
  1069. }
  1070. public getStencilFunctionMask(): number {
  1071. return this._stencilState.stencilFuncMask;
  1072. }
  1073. public setStencilFunction(stencilFunc: number) {
  1074. this._stencilState.stencilFunc = stencilFunc;
  1075. }
  1076. public setStencilFunctionReference(reference: number) {
  1077. this._stencilState.stencilFuncRef = reference;
  1078. }
  1079. public setStencilFunctionMask(mask: number) {
  1080. this._stencilState.stencilFuncMask = mask;
  1081. }
  1082. public getStencilOperationFail(): number {
  1083. return this._stencilState.stencilOpStencilFail;
  1084. }
  1085. public getStencilOperationDepthFail(): number {
  1086. return this._stencilState.stencilOpDepthFail;
  1087. }
  1088. public getStencilOperationPass(): number {
  1089. return this._stencilState.stencilOpStencilDepthPass;
  1090. }
  1091. public setStencilOperationFail(operation: number): void {
  1092. this._stencilState.stencilOpStencilFail = operation;
  1093. }
  1094. public setStencilOperationDepthFail(operation: number): void {
  1095. this._stencilState.stencilOpDepthFail = operation;
  1096. }
  1097. public setStencilOperationPass(operation: number): void {
  1098. this._stencilState.stencilOpStencilDepthPass = operation;
  1099. }
  1100. public setDitheringState(value: boolean): void {
  1101. if (value) {
  1102. this._gl.enable(this._gl.DITHER);
  1103. } else {
  1104. this._gl.disable(this._gl.DITHER);
  1105. }
  1106. }
  1107. /**
  1108. * stop executing a render loop function and remove it from the execution array
  1109. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1110. */
  1111. public stopRenderLoop(renderFunction?: () => void): void {
  1112. if (!renderFunction) {
  1113. this._activeRenderLoops = [];
  1114. return;
  1115. }
  1116. var index = this._activeRenderLoops.indexOf(renderFunction);
  1117. if (index >= 0) {
  1118. this._activeRenderLoops.splice(index, 1);
  1119. }
  1120. }
  1121. public _renderLoop(): void {
  1122. if (!this._contextWasLost) {
  1123. var shouldRender = true;
  1124. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1125. shouldRender = false;
  1126. }
  1127. if (shouldRender) {
  1128. // Start new frame
  1129. this.beginFrame();
  1130. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1131. var renderFunction = this._activeRenderLoops[index];
  1132. renderFunction();
  1133. }
  1134. // Present
  1135. this.endFrame();
  1136. }
  1137. }
  1138. if (this._activeRenderLoops.length > 0) {
  1139. // Register new frame
  1140. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  1141. } else {
  1142. this._renderingQueueLaunched = false;
  1143. }
  1144. }
  1145. /**
  1146. * Register and execute a render loop. The engine can have more than one render function.
  1147. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1148. * @example
  1149. * engine.runRenderLoop(function () {
  1150. * scene.render()
  1151. * })
  1152. */
  1153. public runRenderLoop(renderFunction: () => void): void {
  1154. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1155. return;
  1156. }
  1157. this._activeRenderLoops.push(renderFunction);
  1158. if (!this._renderingQueueLaunched) {
  1159. this._renderingQueueLaunched = true;
  1160. this._bindedRenderFunction = this._renderLoop.bind(this);
  1161. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1162. }
  1163. }
  1164. /**
  1165. * Toggle full screen mode.
  1166. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1167. * @param {any} options - an options object to be sent to the requestFullscreen function
  1168. */
  1169. public switchFullscreen(requestPointerLock: boolean): void {
  1170. if (this.isFullscreen) {
  1171. Tools.ExitFullscreen();
  1172. } else {
  1173. this._pointerLockRequested = requestPointerLock;
  1174. Tools.RequestFullscreen(this._renderingCanvas);
  1175. }
  1176. }
  1177. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1178. this.applyStates();
  1179. var mode = 0;
  1180. if (backBuffer && color) {
  1181. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1182. mode |= this._gl.COLOR_BUFFER_BIT;
  1183. }
  1184. if (depth) {
  1185. this._gl.clearDepth(1.0);
  1186. mode |= this._gl.DEPTH_BUFFER_BIT;
  1187. }
  1188. if (stencil) {
  1189. this._gl.clearStencil(0);
  1190. mode |= this._gl.STENCIL_BUFFER_BIT;
  1191. }
  1192. this._gl.clear(mode);
  1193. }
  1194. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1195. let gl = this._gl;
  1196. // Save state
  1197. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1198. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1199. // Change state
  1200. gl.enable(gl.SCISSOR_TEST);
  1201. gl.scissor(x, y, width, height);
  1202. // Clear
  1203. this.clear(clearColor, true, true, true);
  1204. // Restore state
  1205. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1206. if (curScissor === true) {
  1207. gl.enable(gl.SCISSOR_TEST);
  1208. } else {
  1209. gl.disable(gl.SCISSOR_TEST);
  1210. }
  1211. }
  1212. /**
  1213. * Set the WebGL's viewport
  1214. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1215. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1216. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1217. */
  1218. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1219. var width = requiredWidth || this.getRenderWidth();
  1220. var height = requiredHeight || this.getRenderHeight();
  1221. var x = viewport.x || 0;
  1222. var y = viewport.y || 0;
  1223. this._cachedViewport = viewport;
  1224. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1225. }
  1226. /**
  1227. * Directly set the WebGL Viewport
  1228. * The x, y, width & height are directly passed to the WebGL call
  1229. * @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.
  1230. */
  1231. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  1232. let currentViewport = this._cachedViewport;
  1233. this._cachedViewport = null;
  1234. this._gl.viewport(x, y, width, height);
  1235. return currentViewport;
  1236. }
  1237. public beginFrame(): void {
  1238. this._measureFps();
  1239. }
  1240. public endFrame(): void {
  1241. //force a flush in case we are using a bad OS.
  1242. if (this._badOS) {
  1243. this.flushFramebuffer();
  1244. }
  1245. //submit frame to the vr device, if enabled
  1246. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1247. this._vrDisplayEnabled.submitFrame()
  1248. }
  1249. }
  1250. /**
  1251. * resize the view according to the canvas' size.
  1252. * @example
  1253. * window.addEventListener("resize", function () {
  1254. * engine.resize();
  1255. * });
  1256. */
  1257. public resize(): void {
  1258. // We're not resizing the size of the canvas while in VR mode & presenting
  1259. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  1260. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  1261. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  1262. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1263. }
  1264. }
  1265. /**
  1266. * force a specific size of the canvas
  1267. * @param {number} width - the new canvas' width
  1268. * @param {number} height - the new canvas' height
  1269. */
  1270. public setSize(width: number, height: number): void {
  1271. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1272. return;
  1273. }
  1274. this._renderingCanvas.width = width;
  1275. this._renderingCanvas.height = height;
  1276. for (var index = 0; index < this.scenes.length; index++) {
  1277. var scene = this.scenes[index];
  1278. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1279. var cam = scene.cameras[camIndex];
  1280. cam._currentRenderId = 0;
  1281. }
  1282. }
  1283. if (this.onResizeObservable.hasObservers) {
  1284. this.onResizeObservable.notifyObservers(this);
  1285. }
  1286. }
  1287. //WebVR functions
  1288. public isVRDevicePresent() : boolean {
  1289. return this._vrDisplays != null && this._vrDisplays.length > 0);
  1290. }
  1291. public getVRDevice() : any {
  1292. var devices = this._vrDisplays || [];
  1293. if (devices.length > 0) {
  1294. return devices[0];
  1295. } else {
  1296. Tools.Error("No WebVR devices found!");
  1297. return null;
  1298. }
  1299. }
  1300. public initWebVR(): Observable<any> {
  1301. this.onVRDisplayChangedObservable = new Observable<any>();
  1302. if (!this._onVrDisplayConnect) {
  1303. this._onVrDisplayConnect = (display) => {
  1304. this._vrDisplays = [display];
  1305. // TODO: Notify observable
  1306. };
  1307. this._onVrDisplayDisconnect = () => {
  1308. this._vrDisplays = [];
  1309. // TODO: Notify observable
  1310. };
  1311. }
  1312. this._getVRDisplays();
  1313. return this.onVRDisplayChangedObservable;
  1314. }
  1315. public enableVR(vrDevice) {
  1316. this._vrDisplayEnabled = vrDevice;
  1317. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  1318. }
  1319. public disableVR() {
  1320. if (this._vrDisplayEnabled) {
  1321. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  1322. }
  1323. }
  1324. private _onVRFullScreenTriggered = () => {
  1325. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1326. //get the old size before we change
  1327. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  1328. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1329. //get the width and height, change the render size
  1330. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  1331. var width, height;
  1332. this.setHardwareScalingLevel(1);
  1333. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1334. } else {
  1335. //When the specs are implemented, need to uncomment this.
  1336. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1337. this.setSize(this._oldSize.width, this._oldSize.height);
  1338. this._vrDisplayEnabled = undefined;
  1339. }
  1340. }
  1341. private _getVRDisplays() {
  1342. var getWebVRDevices = (devices: Array<any>) => {
  1343. return this._vrDisplays = devices;
  1344. }
  1345. if (navigator.getVRDisplays) {
  1346. navigator.getVRDisplays().then(getWebVRDevices).catch((error) => {
  1347. // TODO: System CANNOT support WebVR, despite API presence.
  1348. });
  1349. } else {
  1350. // TODO: Browser does not support WebVR
  1351. this._vrDisplays = [];
  1352. }
  1353. }
  1354. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1355. if (this._currentRenderTarget) {
  1356. this.unBindFramebuffer(this._currentRenderTarget);
  1357. }
  1358. this._currentRenderTarget = texture;
  1359. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1360. var gl = this._gl;
  1361. if (texture.isCube) {
  1362. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1363. }
  1364. if (this._cachedViewport && !forceFullscreenViewport) {
  1365. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1366. } else {
  1367. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1368. }
  1369. this.wipeCaches();
  1370. }
  1371. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1372. if (this._currentFramebuffer !== framebuffer) {
  1373. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1374. this._currentFramebuffer = framebuffer;
  1375. }
  1376. }
  1377. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1378. this._currentRenderTarget = null;
  1379. // If MSAA, we need to bitblt back to main texture
  1380. var gl = this._gl;
  1381. if (texture._MSAAFramebuffer) {
  1382. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1383. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1384. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1385. 0, 0, texture.width, texture.height,
  1386. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1387. }
  1388. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1389. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1390. gl.generateMipmap(gl.TEXTURE_2D);
  1391. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1392. }
  1393. if (onBeforeUnbind) {
  1394. if (texture._MSAAFramebuffer) {
  1395. // Bind the correct framebuffer
  1396. this.bindUnboundFramebuffer(texture._framebuffer);
  1397. }
  1398. onBeforeUnbind();
  1399. }
  1400. this.bindUnboundFramebuffer(null);
  1401. }
  1402. public generateMipMapsForCubemap(texture: InternalTexture) {
  1403. if (texture.generateMipMaps) {
  1404. var gl = this._gl;
  1405. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1406. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1407. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1408. }
  1409. }
  1410. public flushFramebuffer(): void {
  1411. this._gl.flush();
  1412. }
  1413. public restoreDefaultFramebuffer(): void {
  1414. if (this._currentRenderTarget) {
  1415. this.unBindFramebuffer(this._currentRenderTarget);
  1416. } else {
  1417. this.bindUnboundFramebuffer(null);
  1418. }
  1419. if (this._cachedViewport) {
  1420. this.setViewport(this._cachedViewport);
  1421. }
  1422. this.wipeCaches();
  1423. }
  1424. // UBOs
  1425. public createUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1426. var ubo = this._gl.createBuffer();
  1427. this.bindUniformBuffer(ubo);
  1428. if (elements instanceof Float32Array) {
  1429. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1430. } else {
  1431. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1432. }
  1433. this.bindUniformBuffer(null);
  1434. ubo.references = 1;
  1435. return ubo;
  1436. }
  1437. public createDynamicUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1438. var ubo = this._gl.createBuffer();
  1439. this.bindUniformBuffer(ubo);
  1440. if (elements instanceof Float32Array) {
  1441. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1442. } else {
  1443. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1444. }
  1445. this.bindUniformBuffer(null);
  1446. ubo.references = 1;
  1447. return ubo;
  1448. }
  1449. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: number[] | Float32Array, offset?: number, count?: number): void {
  1450. this.bindUniformBuffer(uniformBuffer);
  1451. if (offset === undefined) {
  1452. offset = 0;
  1453. }
  1454. if (count === undefined) {
  1455. if (elements instanceof Float32Array) {
  1456. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1457. } else {
  1458. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1459. }
  1460. } else {
  1461. if (elements instanceof Float32Array) {
  1462. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1463. } else {
  1464. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1465. }
  1466. }
  1467. this.bindUniformBuffer(null);
  1468. }
  1469. // VBOs
  1470. private _resetVertexBufferBinding(): void {
  1471. this.bindArrayBuffer(null);
  1472. this._cachedVertexBuffers = null;
  1473. }
  1474. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1475. var vbo = this._gl.createBuffer();
  1476. this.bindArrayBuffer(vbo);
  1477. if (vertices instanceof Float32Array) {
  1478. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1479. } else {
  1480. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1481. }
  1482. this._resetVertexBufferBinding();
  1483. vbo.references = 1;
  1484. return vbo;
  1485. }
  1486. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1487. var vbo = this._gl.createBuffer();
  1488. this.bindArrayBuffer(vbo);
  1489. if (vertices instanceof Float32Array) {
  1490. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1491. } else {
  1492. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1493. }
  1494. this._resetVertexBufferBinding();
  1495. vbo.references = 1;
  1496. return vbo;
  1497. }
  1498. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1499. this.bindArrayBuffer(vertexBuffer);
  1500. if (offset === undefined) {
  1501. offset = 0;
  1502. }
  1503. if (count === undefined) {
  1504. if (vertices instanceof Float32Array) {
  1505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1506. } else {
  1507. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1508. }
  1509. } else {
  1510. if (vertices instanceof Float32Array) {
  1511. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1512. } else {
  1513. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1514. }
  1515. }
  1516. this._resetVertexBufferBinding();
  1517. }
  1518. private _resetIndexBufferBinding(): void {
  1519. this.bindIndexBuffer(null);
  1520. this._cachedIndexBuffer = null;
  1521. }
  1522. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1523. var vbo = this._gl.createBuffer();
  1524. this.bindIndexBuffer(vbo);
  1525. // Check for 32 bits indices
  1526. var arrayBuffer;
  1527. var need32Bits = false;
  1528. if (indices instanceof Uint16Array) {
  1529. arrayBuffer = indices;
  1530. } else {
  1531. //check 32 bit support
  1532. if (this._caps.uintIndices) {
  1533. if (indices instanceof Uint32Array) {
  1534. arrayBuffer = indices;
  1535. need32Bits = true;
  1536. } else {
  1537. //number[] or Int32Array, check if 32 bit is necessary
  1538. for (var index = 0; index < indices.length; index++) {
  1539. if (indices[index] > 65535) {
  1540. need32Bits = true;
  1541. break;
  1542. }
  1543. }
  1544. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1545. }
  1546. } else {
  1547. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1548. arrayBuffer = new Uint16Array(indices);
  1549. }
  1550. }
  1551. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1552. this._resetIndexBufferBinding();
  1553. vbo.references = 1;
  1554. vbo.is32Bits = need32Bits;
  1555. return vbo;
  1556. }
  1557. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1558. if (!this._vaoRecordInProgress) {
  1559. this._unbindVertexArrayObject();
  1560. }
  1561. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1562. }
  1563. public bindUniformBuffer(buffer?: WebGLBuffer): void {
  1564. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1565. }
  1566. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1567. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1568. }
  1569. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1570. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1571. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1572. };
  1573. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1574. if (!this._vaoRecordInProgress) {
  1575. this._unbindVertexArrayObject();
  1576. }
  1577. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1578. }
  1579. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1580. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1581. this._gl.bindBuffer(target, buffer);
  1582. this._currentBoundBuffer[target] = buffer;
  1583. }
  1584. }
  1585. public updateArrayBuffer(data: Float32Array): void {
  1586. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1587. }
  1588. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1589. var pointer = this._currentBufferPointers[indx];
  1590. var changed = false;
  1591. if (!pointer.active) {
  1592. changed = true;
  1593. pointer.active = true;
  1594. pointer.index = indx;
  1595. pointer.size = size;
  1596. pointer.type = type;
  1597. pointer.normalized = normalized;
  1598. pointer.stride = stride;
  1599. pointer.offset = offset;
  1600. pointer.buffer = buffer;
  1601. } else {
  1602. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1603. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1604. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1605. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1606. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1607. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1608. }
  1609. if (changed || this._vaoRecordInProgress) {
  1610. this.bindArrayBuffer(buffer);
  1611. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1612. }
  1613. }
  1614. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1615. if (indexBuffer == null) {
  1616. return;
  1617. }
  1618. if (this._cachedIndexBuffer !== indexBuffer) {
  1619. this._cachedIndexBuffer = indexBuffer;
  1620. this.bindIndexBuffer(indexBuffer);
  1621. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1622. }
  1623. }
  1624. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1625. var attributes = effect.getAttributesNames();
  1626. if (!this._vaoRecordInProgress) {
  1627. this._unbindVertexArrayObject();
  1628. }
  1629. this.unbindAllAttributes();
  1630. for (var index = 0; index < attributes.length; index++) {
  1631. var order = effect.getAttributeLocation(index);
  1632. if (order >= 0) {
  1633. var vertexBuffer = vertexBuffers[attributes[index]];
  1634. if (!vertexBuffer) {
  1635. continue;
  1636. }
  1637. this._gl.enableVertexAttribArray(order);
  1638. if (!this._vaoRecordInProgress) {
  1639. this._vertexAttribArraysEnabled[order] = true;
  1640. }
  1641. var buffer = vertexBuffer.getBuffer();
  1642. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1643. if (vertexBuffer.getIsInstanced()) {
  1644. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1645. if (!this._vaoRecordInProgress) {
  1646. this._currentInstanceLocations.push(order);
  1647. this._currentInstanceBuffers.push(buffer);
  1648. }
  1649. }
  1650. }
  1651. }
  1652. }
  1653. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1654. var vao = this._gl.createVertexArray();
  1655. this._vaoRecordInProgress = true;
  1656. this._gl.bindVertexArray(vao);
  1657. this._mustWipeVertexAttributes = true;
  1658. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1659. this.bindIndexBuffer(indexBuffer);
  1660. this._vaoRecordInProgress = false;
  1661. this._gl.bindVertexArray(null);
  1662. return vao;
  1663. }
  1664. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1665. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1666. this._cachedVertexArrayObject = vertexArrayObject;
  1667. this._gl.bindVertexArray(vertexArrayObject);
  1668. this._cachedVertexBuffers = null;
  1669. this._cachedIndexBuffer = null;
  1670. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1671. this._mustWipeVertexAttributes = true;
  1672. }
  1673. }
  1674. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1675. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1676. this._cachedVertexBuffers = vertexBuffer;
  1677. this._cachedEffectForVertexBuffers = effect;
  1678. let attributesCount = effect.getAttributesCount();
  1679. this._unbindVertexArrayObject();
  1680. this.unbindAllAttributes();
  1681. var offset = 0;
  1682. for (var index = 0; index < attributesCount; index++) {
  1683. if (index < vertexDeclaration.length) {
  1684. var order = effect.getAttributeLocation(index);
  1685. if (order >= 0) {
  1686. this._gl.enableVertexAttribArray(order);
  1687. this._vertexAttribArraysEnabled[order] = true;
  1688. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1689. }
  1690. offset += vertexDeclaration[index] * 4;
  1691. }
  1692. }
  1693. }
  1694. this._bindIndexBufferWithCache(indexBuffer);
  1695. }
  1696. private _unbindVertexArrayObject(): void {
  1697. if (!this._cachedVertexArrayObject) {
  1698. return;
  1699. }
  1700. this._cachedVertexArrayObject = null;
  1701. this._gl.bindVertexArray(null);
  1702. }
  1703. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1704. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1705. this._cachedVertexBuffers = vertexBuffers;
  1706. this._cachedEffectForVertexBuffers = effect;
  1707. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1708. }
  1709. this._bindIndexBufferWithCache(indexBuffer);
  1710. }
  1711. public unbindInstanceAttributes() {
  1712. var boundBuffer;
  1713. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1714. var instancesBuffer = this._currentInstanceBuffers[i];
  1715. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1716. boundBuffer = instancesBuffer;
  1717. this.bindArrayBuffer(instancesBuffer);
  1718. }
  1719. var offsetLocation = this._currentInstanceLocations[i];
  1720. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1721. }
  1722. this._currentInstanceBuffers.length = 0;
  1723. this._currentInstanceLocations.length = 0;
  1724. }
  1725. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1726. this._gl.deleteVertexArray(vao);
  1727. }
  1728. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1729. buffer.references--;
  1730. if (buffer.references === 0) {
  1731. this._gl.deleteBuffer(buffer);
  1732. return true;
  1733. }
  1734. return false;
  1735. }
  1736. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1737. var buffer = this._gl.createBuffer();
  1738. buffer.capacity = capacity;
  1739. this.bindArrayBuffer(buffer);
  1740. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1741. return buffer;
  1742. }
  1743. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1744. this._gl.deleteBuffer(buffer);
  1745. }
  1746. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1747. this.bindArrayBuffer(instancesBuffer);
  1748. if (data) {
  1749. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1750. }
  1751. if ((<any>offsetLocations[0]).index !== undefined) {
  1752. let stride = 0;
  1753. for (let i = 0; i < offsetLocations.length; i++) {
  1754. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1755. stride += ai.attributeSize * 4;
  1756. }
  1757. for (let i = 0; i < offsetLocations.length; i++) {
  1758. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1759. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1760. this._gl.enableVertexAttribArray(ai.index);
  1761. this._vertexAttribArraysEnabled[ai.index] = true;
  1762. }
  1763. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1764. this._gl.vertexAttribDivisor(ai.index, 1);
  1765. this._currentInstanceLocations.push(ai.index);
  1766. this._currentInstanceBuffers.push(instancesBuffer);
  1767. }
  1768. } else {
  1769. for (let index = 0; index < 4; index++) {
  1770. let offsetLocation = <number>offsetLocations[index];
  1771. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1772. this._gl.enableVertexAttribArray(offsetLocation);
  1773. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1774. }
  1775. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1776. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1777. this._currentInstanceLocations.push(offsetLocation);
  1778. this._currentInstanceBuffers.push(instancesBuffer);
  1779. }
  1780. }
  1781. }
  1782. public applyStates() {
  1783. this._depthCullingState.apply(this._gl);
  1784. this._stencilState.apply(this._gl);
  1785. this._alphaState.apply(this._gl);
  1786. }
  1787. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1788. // Apply states
  1789. this.applyStates();
  1790. this._drawCalls.addCount(1, false);
  1791. // Render
  1792. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1793. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1794. if (instancesCount) {
  1795. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1796. return;
  1797. }
  1798. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1799. }
  1800. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1801. // Apply states
  1802. this.applyStates();
  1803. this._drawCalls.addCount(1, false);
  1804. if (instancesCount) {
  1805. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1806. return;
  1807. }
  1808. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1809. }
  1810. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1811. // Apply states
  1812. this.applyStates();
  1813. this._drawCalls.addCount(1, false);
  1814. if (instancesCount) {
  1815. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1816. return;
  1817. }
  1818. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1819. }
  1820. // Shaders
  1821. public _releaseEffect(effect: Effect): void {
  1822. if (this._compiledEffects[effect._key]) {
  1823. delete this._compiledEffects[effect._key];
  1824. if (effect.getProgram()) {
  1825. this._gl.deleteProgram(effect.getProgram());
  1826. }
  1827. }
  1828. }
  1829. /**
  1830. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1831. * @param samplers An array of string used to represent textures
  1832. */
  1833. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  1834. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1835. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1836. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1837. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1838. if (this._compiledEffects[name]) {
  1839. var compiledEffect = <Effect>this._compiledEffects[name];
  1840. if (onCompiled && compiledEffect.isReady()) {
  1841. onCompiled(compiledEffect);
  1842. }
  1843. return compiledEffect;
  1844. }
  1845. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1846. effect._key = name;
  1847. this._compiledEffects[name] = effect;
  1848. return effect;
  1849. }
  1850. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1851. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1852. return this.createEffect(
  1853. {
  1854. vertex: "particles",
  1855. fragmentElement: fragmentName
  1856. },
  1857. ["position", "color", "options"],
  1858. ["view", "projection"].concat(uniformsNames),
  1859. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1860. }
  1861. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1862. context = context || this._gl;
  1863. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1864. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1865. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1866. var shaderProgram = context.createProgram();
  1867. context.attachShader(shaderProgram, vertexShader);
  1868. context.attachShader(shaderProgram, fragmentShader);
  1869. context.linkProgram(shaderProgram);
  1870. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1871. if (!linked) {
  1872. context.validateProgram(shaderProgram);
  1873. var error = context.getProgramInfoLog(shaderProgram);
  1874. if (error) {
  1875. throw new Error(error);
  1876. }
  1877. }
  1878. context.deleteShader(vertexShader);
  1879. context.deleteShader(fragmentShader);
  1880. return shaderProgram;
  1881. }
  1882. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1883. var results = [];
  1884. for (var index = 0; index < uniformsNames.length; index++) {
  1885. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1886. }
  1887. return results;
  1888. }
  1889. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1890. var results = [];
  1891. for (var index = 0; index < attributesNames.length; index++) {
  1892. try {
  1893. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1894. } catch (e) {
  1895. results.push(-1);
  1896. }
  1897. }
  1898. return results;
  1899. }
  1900. public enableEffect(effect: Effect): void {
  1901. // Use program
  1902. this.setProgram(effect.getProgram());
  1903. this._currentEffect = effect;
  1904. if (effect.onBind) {
  1905. effect.onBind(effect);
  1906. }
  1907. effect.onBindObservable.notifyObservers(effect);
  1908. }
  1909. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1910. if (!uniform)
  1911. return;
  1912. this._gl.uniform1iv(uniform, array);
  1913. }
  1914. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1915. if (!uniform || array.length % 2 !== 0)
  1916. return;
  1917. this._gl.uniform2iv(uniform, array);
  1918. }
  1919. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1920. if (!uniform || array.length % 3 !== 0)
  1921. return;
  1922. this._gl.uniform3iv(uniform, array);
  1923. }
  1924. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1925. if (!uniform || array.length % 4 !== 0)
  1926. return;
  1927. this._gl.uniform4iv(uniform, array);
  1928. }
  1929. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1930. if (!uniform)
  1931. return;
  1932. this._gl.uniform1fv(uniform, array);
  1933. }
  1934. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1935. if (!uniform || array.length % 2 !== 0)
  1936. return;
  1937. this._gl.uniform2fv(uniform, array);
  1938. }
  1939. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1940. if (!uniform || array.length % 3 !== 0)
  1941. return;
  1942. this._gl.uniform3fv(uniform, array);
  1943. }
  1944. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1945. if (!uniform || array.length % 4 !== 0)
  1946. return;
  1947. this._gl.uniform4fv(uniform, array);
  1948. }
  1949. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1950. if (!uniform)
  1951. return;
  1952. this._gl.uniform1fv(uniform, <any>array);
  1953. }
  1954. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1955. if (!uniform || array.length % 2 !== 0)
  1956. return;
  1957. this._gl.uniform2fv(uniform, <any>array);
  1958. }
  1959. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1960. if (!uniform || array.length % 3 !== 0)
  1961. return;
  1962. this._gl.uniform3fv(uniform, <any>array);
  1963. }
  1964. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1965. if (!uniform || array.length % 4 !== 0)
  1966. return;
  1967. this._gl.uniform4fv(uniform, <any>array);
  1968. }
  1969. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1970. if (!uniform)
  1971. return;
  1972. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1973. }
  1974. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1975. if (!uniform)
  1976. return;
  1977. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1978. }
  1979. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1980. if (!uniform)
  1981. return;
  1982. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1983. }
  1984. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1985. if (!uniform)
  1986. return;
  1987. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1988. }
  1989. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1990. if (!uniform)
  1991. return;
  1992. this._gl.uniform1f(uniform, value);
  1993. }
  1994. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1995. if (!uniform)
  1996. return;
  1997. this._gl.uniform2f(uniform, x, y);
  1998. }
  1999. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  2000. if (!uniform)
  2001. return;
  2002. this._gl.uniform3f(uniform, x, y, z);
  2003. }
  2004. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  2005. if (!uniform)
  2006. return;
  2007. this._gl.uniform1i(uniform, bool);
  2008. }
  2009. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  2010. if (!uniform)
  2011. return;
  2012. this._gl.uniform4f(uniform, x, y, z, w);
  2013. }
  2014. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  2015. if (!uniform)
  2016. return;
  2017. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2018. }
  2019. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  2020. if (!uniform)
  2021. return;
  2022. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2023. }
  2024. // States
  2025. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2026. // Culling
  2027. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  2028. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  2029. var cullFace = this.cullBackFaces ? showSide : hideSide;
  2030. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  2031. if (culling) {
  2032. this._depthCullingState.cullFace = cullFace;
  2033. this._depthCullingState.cull = true;
  2034. } else {
  2035. this._depthCullingState.cull = false;
  2036. }
  2037. }
  2038. // Z offset
  2039. this.setZOffset(zOffset);
  2040. }
  2041. public setZOffset(value: number): void {
  2042. this._depthCullingState.zOffset = value;
  2043. }
  2044. public getZOffset(): number {
  2045. return this._depthCullingState.zOffset;
  2046. }
  2047. public setDepthBuffer(enable: boolean): void {
  2048. this._depthCullingState.depthTest = enable;
  2049. }
  2050. public getDepthWrite(): boolean {
  2051. return this._depthCullingState.depthMask;
  2052. }
  2053. public setDepthWrite(enable: boolean): void {
  2054. this._depthCullingState.depthMask = enable;
  2055. }
  2056. public setColorWrite(enable: boolean): void {
  2057. this._gl.colorMask(enable, enable, enable, enable);
  2058. this._colorWrite = enable;
  2059. }
  2060. public getColorWrite(): boolean {
  2061. return this._colorWrite;
  2062. }
  2063. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2064. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2065. }
  2066. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2067. if (this._alphaMode === mode) {
  2068. return;
  2069. }
  2070. switch (mode) {
  2071. case Engine.ALPHA_DISABLE:
  2072. this._alphaState.alphaBlend = false;
  2073. break;
  2074. case Engine.ALPHA_PREMULTIPLIED:
  2075. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2076. this._alphaState.alphaBlend = true;
  2077. break;
  2078. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2080. this._alphaState.alphaBlend = true;
  2081. break;
  2082. case Engine.ALPHA_COMBINE:
  2083. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2084. this._alphaState.alphaBlend = true;
  2085. break;
  2086. case Engine.ALPHA_ONEONE:
  2087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2088. this._alphaState.alphaBlend = true;
  2089. break;
  2090. case Engine.ALPHA_ADD:
  2091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2092. this._alphaState.alphaBlend = true;
  2093. break;
  2094. case Engine.ALPHA_SUBTRACT:
  2095. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2096. this._alphaState.alphaBlend = true;
  2097. break;
  2098. case Engine.ALPHA_MULTIPLY:
  2099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2100. this._alphaState.alphaBlend = true;
  2101. break;
  2102. case Engine.ALPHA_MAXIMIZED:
  2103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2104. this._alphaState.alphaBlend = true;
  2105. break;
  2106. case Engine.ALPHA_INTERPOLATE:
  2107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2108. this._alphaState.alphaBlend = true;
  2109. break;
  2110. case Engine.ALPHA_SCREENMODE:
  2111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2112. this._alphaState.alphaBlend = true;
  2113. break;
  2114. }
  2115. if (!noDepthWriteChange) {
  2116. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2117. }
  2118. this._alphaMode = mode;
  2119. }
  2120. public getAlphaMode(): number {
  2121. return this._alphaMode;
  2122. }
  2123. public setAlphaTesting(enable: boolean): void {
  2124. this._alphaTest = enable;
  2125. }
  2126. public getAlphaTesting(): boolean {
  2127. return !!this._alphaTest;
  2128. }
  2129. // Textures
  2130. public wipeCaches(bruteForce?: boolean): void {
  2131. if (this.preventCacheWipeBetweenFrames) {
  2132. return;
  2133. }
  2134. this.resetTextureCache();
  2135. this._currentEffect = null;
  2136. // 6/8/2017: deltakosh: Should not be required anymore.
  2137. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  2138. if (bruteForce) {
  2139. this._currentProgram = null;
  2140. this._stencilState.reset();
  2141. this._depthCullingState.reset();
  2142. this.setDepthFunctionToLessOrEqual();
  2143. this._alphaState.reset();
  2144. }
  2145. this._cachedVertexBuffers = null;
  2146. this._cachedIndexBuffer = null;
  2147. this._cachedEffectForVertexBuffers = null;
  2148. this._unbindVertexArrayObject();
  2149. this.bindIndexBuffer(null);
  2150. this.bindArrayBuffer(null);
  2151. }
  2152. /**
  2153. * Set the compressed texture format to use, based on the formats you have, and the formats
  2154. * supported by the hardware / browser.
  2155. *
  2156. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2157. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2158. * to API arguments needed to compressed textures. This puts the burden on the container
  2159. * generator to house the arcane code for determining these for current & future formats.
  2160. *
  2161. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2162. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2163. *
  2164. * Note: The result of this call is not taken into account when a texture is base64.
  2165. *
  2166. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2167. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2168. *
  2169. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2170. * @returns The extension selected.
  2171. */
  2172. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  2173. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2174. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2175. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2176. return this._textureFormatInUse = this._texturesSupported[i];
  2177. }
  2178. }
  2179. }
  2180. // actively set format to nothing, to allow this to be called more than once
  2181. // and possibly fail the 2nd time
  2182. return this._textureFormatInUse = null;
  2183. }
  2184. public _createTexture(): WebGLTexture {
  2185. return this._gl.createTexture();
  2186. }
  2187. /**
  2188. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2189. * @param {string} urlArg- This contains one of the following:
  2190. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2191. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2192. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2193. *
  2194. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2195. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2196. * @param {Scene} scene- Needed for loading to the correct scene.
  2197. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2198. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2199. * @param {callback} onError- Optional callback to be called upon failure.
  2200. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2201. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2202. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2203. *
  2204. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2205. */
  2206. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: ArrayBuffer | HTMLImageElement = null, fallBack?: InternalTexture, format?: number): InternalTexture {
  2207. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2208. var fromData = url.substr(0, 5) === "data:";
  2209. var fromBlob = url.substr(0, 5) === "blob:";
  2210. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2211. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2212. // establish the file extension, if possible
  2213. var lastDot = url.lastIndexOf('.');
  2214. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2215. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2216. var isTGA = (extension === ".tga");
  2217. // determine if a ktx file should be substituted
  2218. var isKTX = false;
  2219. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2220. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2221. isKTX = true;
  2222. }
  2223. if (scene) {
  2224. scene._addPendingData(texture);
  2225. }
  2226. texture.url = url;
  2227. texture.generateMipMaps = !noMipmap;
  2228. texture.samplingMode = samplingMode;
  2229. texture.invertY = invertY;
  2230. if (!this._doNotHandleContextLost) {
  2231. // Keep a link to the buffer only if we plan to handle context lost
  2232. texture._buffer = buffer;
  2233. }
  2234. if (onLoad) {
  2235. texture.onLoadedObservable.add(onLoad);
  2236. }
  2237. if (!fallBack) this._internalTexturesCache.push(texture);
  2238. var onerror = () => {
  2239. if (scene) {
  2240. scene._removePendingData(texture);
  2241. }
  2242. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2243. if (isKTX) {
  2244. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2245. } else if (onError) {
  2246. onError();
  2247. }
  2248. };
  2249. var callback: (arrayBuffer: any) => void;
  2250. // processing for non-image formats
  2251. if (isKTX || isTGA || isDDS) {
  2252. if (isKTX) {
  2253. callback = (data) => {
  2254. var ktx = new Internals.KhronosTextureContainer(data, 1);
  2255. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2256. ktx.uploadLevels(this._gl, !noMipmap);
  2257. return false;
  2258. }, samplingMode);
  2259. };
  2260. } else if (isTGA) {
  2261. callback = (arrayBuffer) => {
  2262. var data = new Uint8Array(arrayBuffer);
  2263. var header = Internals.TGATools.GetTGAHeader(data);
  2264. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2265. Internals.TGATools.UploadContent(this._gl, data);
  2266. return false;
  2267. }, samplingMode);
  2268. };
  2269. } else if (isDDS) {
  2270. callback = (data) => {
  2271. var info = Internals.DDSTools.GetDDSInfo(data);
  2272. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2273. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2274. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2275. return false;
  2276. }, samplingMode);
  2277. };
  2278. }
  2279. if (!buffer) {
  2280. Tools.LoadFile(url, data => {
  2281. callback(data);
  2282. }, null, scene ? scene.database : null, true, onerror);
  2283. } else {
  2284. callback(buffer);
  2285. }
  2286. // image format processing
  2287. } else {
  2288. var onload = (img) => {
  2289. if (fromBlob && !this._doNotHandleContextLost) {
  2290. // We need to store the image if we need to rebuild the texture
  2291. // in case of a webgl context lost
  2292. texture._buffer = img;
  2293. }
  2294. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2295. let gl = this._gl;
  2296. var isPot = (img.width === potWidth && img.height === potHeight);
  2297. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2298. if (isPot) {
  2299. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2300. return false;
  2301. }
  2302. // Using shaders to rescale because canvas.drawImage is lossy
  2303. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2304. this._bindTextureDirectly(gl.TEXTURE_2D, source);
  2305. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2306. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2310. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2311. this._releaseTexture(source);
  2312. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2313. continuationCallback();
  2314. });
  2315. return true;
  2316. }, samplingMode);
  2317. };
  2318. if (!fromData || isBase64)
  2319. if (buffer instanceof HTMLImageElement) {
  2320. onload(buffer);
  2321. } else {
  2322. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2323. }
  2324. else if (buffer instanceof Array || typeof buffer === "string")
  2325. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2326. else
  2327. onload(buffer);
  2328. }
  2329. return texture;
  2330. }
  2331. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Scene, internalFormat: number, onComplete: () => void): void {
  2332. let rtt = this.createRenderTargetTexture({
  2333. width: destination.width,
  2334. height: destination.height,
  2335. }, {
  2336. generateMipMaps: false,
  2337. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2338. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2339. generateDepthBuffer: false,
  2340. generateStencilBuffer: false
  2341. }
  2342. );
  2343. if (!this._rescalePostProcess) {
  2344. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2345. }
  2346. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2347. this._rescalePostProcess.onApply = function (effect) {
  2348. effect._bindTexture("textureSampler", source);
  2349. }
  2350. let hostingScene = scene;
  2351. if (!hostingScene) {
  2352. hostingScene = this.scenes[this.scenes.length - 1];
  2353. }
  2354. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt);
  2355. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination);
  2356. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2357. this.unBindFramebuffer(rtt);
  2358. this._releaseTexture(rtt);
  2359. if (onComplete) {
  2360. onComplete();
  2361. }
  2362. });
  2363. }
  2364. private _getInternalFormat(format: number): number {
  2365. var internalFormat = this._gl.RGBA;
  2366. switch (format) {
  2367. case Engine.TEXTUREFORMAT_ALPHA:
  2368. internalFormat = this._gl.ALPHA;
  2369. break;
  2370. case Engine.TEXTUREFORMAT_LUMINANCE:
  2371. internalFormat = this._gl.LUMINANCE;
  2372. break;
  2373. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2374. internalFormat = this._gl.LUMINANCE_ALPHA;
  2375. break;
  2376. case Engine.TEXTUREFORMAT_RGB:
  2377. internalFormat = this._gl.RGB;
  2378. break;
  2379. case Engine.TEXTUREFORMAT_RGBA:
  2380. internalFormat = this._gl.RGBA;
  2381. break;
  2382. }
  2383. return internalFormat;
  2384. }
  2385. public updateRawTexture(texture: InternalTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  2386. var internalFormat = this._getInternalFormat(format);
  2387. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2388. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2389. if (!this._doNotHandleContextLost) {
  2390. texture._bufferView = data;
  2391. texture.format = format;
  2392. texture.invertY = invertY;
  2393. texture._compression = compression;
  2394. }
  2395. if (texture.width % 4 !== 0) {
  2396. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2397. }
  2398. if (compression) {
  2399. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  2400. } else {
  2401. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  2402. }
  2403. if (texture.generateMipMaps) {
  2404. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2405. }
  2406. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2407. this.resetTextureCache();
  2408. texture.isReady = true;
  2409. }
  2410. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  2411. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2412. texture.baseWidth = width;
  2413. texture.baseHeight = height;
  2414. texture.width = width;
  2415. texture.height = height;
  2416. texture.format = format;
  2417. texture.generateMipMaps = generateMipMaps;
  2418. texture.samplingMode = samplingMode;
  2419. texture.invertY = invertY;
  2420. texture._compression = compression;
  2421. if (!this._doNotHandleContextLost) {
  2422. texture._bufferView = data;
  2423. }
  2424. this.updateRawTexture(texture, data, format, invertY, compression);
  2425. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2426. // Filters
  2427. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2428. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2429. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2430. if (generateMipMaps) {
  2431. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2432. }
  2433. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2434. this._internalTexturesCache.push(texture);
  2435. return texture;
  2436. }
  2437. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2438. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2439. texture.baseWidth = width;
  2440. texture.baseHeight = height;
  2441. if (generateMipMaps) {
  2442. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2443. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2444. }
  2445. this.resetTextureCache();
  2446. texture.width = width;
  2447. texture.height = height;
  2448. texture.isReady = false;
  2449. texture.generateMipMaps = generateMipMaps;
  2450. texture.samplingMode = samplingMode;
  2451. this.updateTextureSamplingMode(samplingMode, texture);
  2452. this._internalTexturesCache.push(texture);
  2453. return texture;
  2454. }
  2455. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2456. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2457. if (texture.isCube) {
  2458. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  2459. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2460. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2461. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2462. } else {
  2463. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2464. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2465. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2466. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2467. }
  2468. texture.samplingMode = samplingMode;
  2469. }
  2470. public updateDynamicTexture(texture: InternalTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2471. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2472. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2473. if (premulAlpha) {
  2474. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2475. }
  2476. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2477. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2478. if (texture.generateMipMaps) {
  2479. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2480. }
  2481. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2482. if (premulAlpha) {
  2483. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2484. }
  2485. this.resetTextureCache();
  2486. texture.isReady = true;
  2487. }
  2488. public updateVideoTexture(texture: InternalTexture, video: HTMLVideoElement, invertY: boolean): void {
  2489. if (texture._isDisabled) {
  2490. return;
  2491. }
  2492. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2493. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2494. try {
  2495. // Testing video texture support
  2496. if (this._videoTextureSupported === undefined) {
  2497. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2498. if (this._gl.getError() !== 0) {
  2499. this._videoTextureSupported = false;
  2500. } else {
  2501. this._videoTextureSupported = true;
  2502. }
  2503. }
  2504. // Copy video through the current working canvas if video texture is not supported
  2505. if (!this._videoTextureSupported) {
  2506. if (!texture._workingCanvas) {
  2507. texture._workingCanvas = document.createElement("canvas");
  2508. texture._workingContext = texture._workingCanvas.getContext("2d");
  2509. texture._workingCanvas.width = texture.width;
  2510. texture._workingCanvas.height = texture.height;
  2511. }
  2512. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2513. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2514. } else {
  2515. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2516. }
  2517. if (texture.generateMipMaps) {
  2518. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2519. }
  2520. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2521. this.resetTextureCache();
  2522. texture.isReady = true;
  2523. } catch (ex) {
  2524. // Something unexpected
  2525. // Let's disable the texture
  2526. texture._isDisabled = true;
  2527. }
  2528. }
  2529. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2530. let fullOptions = new RenderTargetCreationOptions();
  2531. if (options !== undefined && typeof options === "object") {
  2532. fullOptions.generateMipMaps = options.generateMipMaps;
  2533. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2534. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2535. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2536. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2537. } else {
  2538. fullOptions.generateMipMaps = <boolean>options;
  2539. fullOptions.generateDepthBuffer = true;
  2540. fullOptions.generateStencilBuffer = false;
  2541. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2542. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2543. }
  2544. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2545. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2546. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2547. }
  2548. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2549. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2550. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2551. }
  2552. var gl = this._gl;
  2553. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2554. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2555. var width = size.width || size;
  2556. var height = size.height || size;
  2557. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  2558. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2559. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2560. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2561. }
  2562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2566. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  2567. // Create the framebuffer
  2568. var framebuffer = gl.createFramebuffer();
  2569. this.bindUnboundFramebuffer(framebuffer);
  2570. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2571. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  2572. if (fullOptions.generateMipMaps) {
  2573. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2574. }
  2575. // Unbind
  2576. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2577. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2578. this.bindUnboundFramebuffer(null);
  2579. texture._framebuffer = framebuffer;
  2580. texture.baseWidth = width;
  2581. texture.baseHeight = height;
  2582. texture.width = width;
  2583. texture.height = height;
  2584. texture.isReady = true;
  2585. texture.samples = 1;
  2586. texture.generateMipMaps = fullOptions.generateMipMaps;
  2587. texture.samplingMode = fullOptions.samplingMode;
  2588. texture.type = fullOptions.type;
  2589. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2590. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  2591. this.resetTextureCache();
  2592. this._internalTexturesCache.push(texture);
  2593. return texture;
  2594. }
  2595. public createMultipleRenderTarget(size: any, options): InternalTexture[] {
  2596. var generateMipMaps = false;
  2597. var generateDepthBuffer = true;
  2598. var generateStencilBuffer = false;
  2599. var generateDepthTexture = false;
  2600. var textureCount = 1;
  2601. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2602. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2603. var types = [], samplingModes = [];
  2604. if (options !== undefined) {
  2605. generateMipMaps = options.generateMipMaps;
  2606. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2607. generateStencilBuffer = options.generateStencilBuffer;
  2608. generateDepthTexture = options.generateDepthTexture;
  2609. textureCount = options.textureCount || 1;
  2610. if (options.types) {
  2611. types = options.types;
  2612. }
  2613. if (options.samplingModes) {
  2614. samplingModes = options.samplingModes;
  2615. }
  2616. }
  2617. var gl = this._gl;
  2618. // Create the framebuffer
  2619. var framebuffer = gl.createFramebuffer();
  2620. this.bindUnboundFramebuffer(framebuffer);
  2621. var width = size.width || size;
  2622. var height = size.height || size;
  2623. var textures = [];
  2624. var attachments = []
  2625. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2626. for (var i = 0; i < textureCount; i++) {
  2627. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2628. var type = types[i] || defaultType;
  2629. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2630. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2631. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2632. }
  2633. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2634. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2635. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2636. }
  2637. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2638. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2639. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2640. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2641. }
  2642. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2643. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2644. textures.push(texture);
  2645. attachments.push(attachment);
  2646. gl.activeTexture(gl["TEXTURE" + i]);
  2647. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  2648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2651. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2652. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2653. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2654. if (generateMipMaps) {
  2655. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2656. }
  2657. // Unbind
  2658. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2659. texture._framebuffer = framebuffer;
  2660. texture._depthStencilBuffer = depthStencilBuffer;
  2661. texture.baseWidth = width;
  2662. texture.baseHeight = height;
  2663. texture.width = width;
  2664. texture.height = height;
  2665. texture.isReady = true;
  2666. texture.samples = 1;
  2667. texture.generateMipMaps = generateMipMaps;
  2668. texture.samplingMode = samplingMode;
  2669. texture.type = type;
  2670. texture._generateDepthBuffer = generateDepthBuffer;
  2671. texture._generateStencilBuffer = generateStencilBuffer;
  2672. this._internalTexturesCache.push(texture);
  2673. }
  2674. if (generateDepthTexture && this._caps.depthTextureExtension) {
  2675. // Depth texture
  2676. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2677. gl.activeTexture(gl.TEXTURE0);
  2678. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  2679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2683. gl.texImage2D(
  2684. gl.TEXTURE_2D,
  2685. 0,
  2686. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  2687. width,
  2688. height,
  2689. 0,
  2690. gl.DEPTH_COMPONENT,
  2691. gl.UNSIGNED_SHORT,
  2692. null
  2693. );
  2694. gl.framebufferTexture2D(
  2695. gl.FRAMEBUFFER,
  2696. gl.DEPTH_ATTACHMENT,
  2697. gl.TEXTURE_2D,
  2698. depthTexture._webGLTexture,
  2699. 0
  2700. );
  2701. depthTexture._framebuffer = framebuffer;
  2702. depthTexture.baseWidth = width;
  2703. depthTexture.baseHeight = height;
  2704. depthTexture.width = width;
  2705. depthTexture.height = height;
  2706. depthTexture.isReady = true;
  2707. depthTexture.samples = 1;
  2708. depthTexture.generateMipMaps = generateMipMaps;
  2709. depthTexture.samplingMode = gl.NEAREST;
  2710. depthTexture._generateDepthBuffer = generateDepthBuffer;
  2711. depthTexture._generateStencilBuffer = generateStencilBuffer;
  2712. textures.push(depthTexture)
  2713. this._internalTexturesCache.push(depthTexture);
  2714. }
  2715. gl.drawBuffers(attachments);
  2716. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2717. this.bindUnboundFramebuffer(null);
  2718. this.resetTextureCache();
  2719. return textures;
  2720. }
  2721. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2722. var depthStencilBuffer: WebGLRenderbuffer = null;
  2723. var gl = this._gl;
  2724. // Create the depth/stencil buffer
  2725. if (generateStencilBuffer) {
  2726. depthStencilBuffer = gl.createRenderbuffer();
  2727. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2728. if (samples > 1) {
  2729. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  2730. } else {
  2731. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2732. }
  2733. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2734. }
  2735. else if (generateDepthBuffer) {
  2736. depthStencilBuffer = gl.createRenderbuffer();
  2737. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2738. if (samples > 1) {
  2739. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2740. } else {
  2741. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2742. }
  2743. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2744. }
  2745. return depthStencilBuffer;
  2746. }
  2747. public updateRenderTargetTextureSampleCount(texture: InternalTexture, samples: number): number {
  2748. if (this.webGLVersion < 2) {
  2749. return 1;
  2750. }
  2751. if (texture.samples === samples) {
  2752. return samples;
  2753. }
  2754. var gl = this._gl;
  2755. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2756. // Dispose previous render buffers
  2757. if (texture._depthStencilBuffer) {
  2758. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2759. }
  2760. if (texture._MSAAFramebuffer) {
  2761. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2762. }
  2763. if (texture._MSAARenderBuffer) {
  2764. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2765. }
  2766. if (samples > 1) {
  2767. texture._MSAAFramebuffer = gl.createFramebuffer();
  2768. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2769. var colorRenderbuffer = gl.createRenderbuffer();
  2770. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2771. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  2772. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2773. texture._MSAARenderBuffer = colorRenderbuffer;
  2774. } else {
  2775. this.bindUnboundFramebuffer(texture._framebuffer);
  2776. }
  2777. texture.samples = samples;
  2778. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  2779. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2780. this.bindUnboundFramebuffer(null);
  2781. return samples;
  2782. }
  2783. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  2784. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  2785. }
  2786. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  2787. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  2788. }
  2789. public createRenderTargetCubeTexture(size: number, options?: RenderTargetCreationOptions): InternalTexture {
  2790. var gl = this._gl;
  2791. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2792. var generateMipMaps = true;
  2793. var generateDepthBuffer = true;
  2794. var generateStencilBuffer = false;
  2795. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2796. if (options !== undefined) {
  2797. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  2798. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2799. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2800. if (options.samplingMode !== undefined) {
  2801. samplingMode = options.samplingMode;
  2802. }
  2803. }
  2804. texture.isCube = true;
  2805. texture.generateMipMaps = generateMipMaps;
  2806. texture.samples = 1;
  2807. texture.samplingMode = samplingMode;
  2808. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2809. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2810. for (var face = 0; face < 6; face++) {
  2811. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2812. }
  2813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2817. // Create the framebuffer
  2818. var framebuffer = gl.createFramebuffer();
  2819. this.bindUnboundFramebuffer(framebuffer);
  2820. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2821. // Mipmaps
  2822. if (texture.generateMipMaps) {
  2823. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2824. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2825. }
  2826. // Unbind
  2827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2828. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2829. this.bindUnboundFramebuffer(null);
  2830. texture._framebuffer = framebuffer;
  2831. texture.width = size;
  2832. texture.height = size;
  2833. texture.isReady = true;
  2834. this.resetTextureCache();
  2835. this._internalTexturesCache.push(texture);
  2836. return texture;
  2837. }
  2838. public createPrefilteredCubeTexture(rootUrl: string, scene: Scene, scale: number, offset: number, onLoad: (internalTexture: InternalTexture) => void, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2839. var callback = (loadData) => {
  2840. if (!loadData) {
  2841. if (onLoad) {
  2842. onLoad(null);
  2843. }
  2844. return;
  2845. }
  2846. let texture = loadData.texture as InternalTexture;
  2847. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  2848. texture._lodGenerationScale = scale;
  2849. texture._lodGenerationOffset = offset;
  2850. if (this._caps.textureLOD) {
  2851. // Do not add extra process if texture lod is supported.
  2852. if (onLoad) {
  2853. onLoad(texture);
  2854. }
  2855. return;
  2856. }
  2857. const mipSlices = 3;
  2858. var gl = this._gl;
  2859. const width = loadData.width;
  2860. if (!width) {
  2861. return;
  2862. }
  2863. const textures: BaseTexture[] = [];
  2864. for (let i = 0; i < mipSlices; i++) {
  2865. //compute LOD from even spacing in smoothness (matching shader calculation)
  2866. let smoothness = i / (mipSlices - 1);
  2867. let roughness = 1 - smoothness;
  2868. let minLODIndex = offset; // roughness = 0
  2869. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  2870. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  2871. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  2872. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2873. glTextureFromLod.isCube = true;
  2874. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  2875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2879. if (loadData.isDDS) {
  2880. var info: Internals.DDSInfo = loadData.info;
  2881. var data: any = loadData.data;
  2882. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2883. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  2884. }
  2885. else {
  2886. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  2887. }
  2888. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2889. // Wrap in a base texture for easy binding.
  2890. const lodTexture = new BaseTexture(scene);
  2891. lodTexture.isCube = true;
  2892. lodTexture._texture = glTextureFromLod;
  2893. glTextureFromLod.isReady = true;
  2894. textures.push(lodTexture);
  2895. }
  2896. texture._lodTextureHigh = textures[2];
  2897. texture._lodTextureMid = textures[1];
  2898. texture._lodTextureLow = textures[0];
  2899. if (onLoad) {
  2900. onLoad(texture);
  2901. }
  2902. };
  2903. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  2904. }
  2905. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: (data?: any) => void = null, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2906. var gl = this._gl;
  2907. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  2908. texture.isCube = true;
  2909. texture.url = rootUrl;
  2910. texture.generateMipMaps = !noMipmap;
  2911. if (!this._doNotHandleContextLost) {
  2912. texture._extension = forcedExtension;
  2913. texture._files = files;
  2914. }
  2915. var isKTX = false;
  2916. var isDDS = false;
  2917. var lastDot = rootUrl.lastIndexOf('.');
  2918. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  2919. if (this._textureFormatInUse) {
  2920. extension = this._textureFormatInUse;
  2921. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2922. isKTX = true;
  2923. } else {
  2924. isDDS = (extension === ".dds");
  2925. }
  2926. if (isKTX) {
  2927. Tools.LoadFile(rootUrl, data => {
  2928. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2929. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2930. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2931. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2932. ktx.uploadLevels(this._gl, !noMipmap);
  2933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2935. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2937. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2938. this.resetTextureCache();
  2939. texture.width = ktx.pixelWidth;
  2940. texture.height = ktx.pixelHeight;
  2941. texture.isReady = true;
  2942. }, null, null, true, onError);
  2943. } else if (isDDS) {
  2944. Tools.LoadFile(rootUrl, data => {
  2945. var info = Internals.DDSTools.GetDDSInfo(data);
  2946. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2947. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2948. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2949. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  2950. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2951. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2952. }
  2953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2957. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2958. this.resetTextureCache();
  2959. texture.width = info.width;
  2960. texture.height = info.height;
  2961. texture.isReady = true;
  2962. texture.type = info.textureType;
  2963. if (onLoad) {
  2964. onLoad({ isDDS: true, width: info.width, info, data, texture });
  2965. }
  2966. }, null, null, true, onError);
  2967. } else {
  2968. cascadeLoad(rootUrl, scene, imgs => {
  2969. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  2970. var height = width;
  2971. this._prepareWorkingCanvas();
  2972. this._workingCanvas.width = width;
  2973. this._workingCanvas.height = height;
  2974. var faces = [
  2975. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2976. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2977. ];
  2978. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2979. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2980. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2981. for (var index = 0; index < faces.length; index++) {
  2982. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2983. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2984. }
  2985. if (!noMipmap) {
  2986. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2987. }
  2988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2991. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2992. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2993. this.resetTextureCache();
  2994. texture.width = width;
  2995. texture.height = height;
  2996. texture.isReady = true;
  2997. texture.format = format;
  2998. texture.onLoadedObservable.notifyObservers(texture);
  2999. texture.onLoadedObservable.clear();
  3000. if (onLoad) {
  3001. onLoad();
  3002. }
  3003. }, files, onError);
  3004. }
  3005. this._internalTexturesCache.push(texture);
  3006. return texture;
  3007. }
  3008. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: string = null, level = 0): void {
  3009. texture._bufferViewArray = data;
  3010. texture.format = format;
  3011. texture.type = type;
  3012. texture.invertY = invertY;
  3013. texture._compression = compression;
  3014. var gl = this._gl;
  3015. var textureType = this._getWebGLTextureType(type);
  3016. var internalFormat = this._getInternalFormat(format);
  3017. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3018. var needConversion = false;
  3019. if (internalFormat === gl.RGB) {
  3020. internalFormat = gl.RGBA;
  3021. needConversion = true;
  3022. }
  3023. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  3024. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3025. if (texture.width % 4 !== 0) {
  3026. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3027. }
  3028. // Data are known to be in +X +Y +Z -X -Y -Z
  3029. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3030. let faceData = data[faceIndex];
  3031. if (compression) {
  3032. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  3033. } else {
  3034. if (needConversion) {
  3035. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3036. }
  3037. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3038. }
  3039. }
  3040. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3041. if (isPot && texture.generateMipMaps && level === 0) {
  3042. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3043. }
  3044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3045. this.resetTextureCache();
  3046. texture.isReady = true;
  3047. }
  3048. public createRawCubeTexture(data: ArrayBufferView[], size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  3049. var gl = this._gl;
  3050. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3051. texture.isCube = true;
  3052. texture.generateMipMaps = generateMipMaps;
  3053. texture.format = format;
  3054. texture.type = type;
  3055. if (!this._doNotHandleContextLost) {
  3056. texture._bufferViewArray = data;
  3057. }
  3058. var textureType = this._getWebGLTextureType(type);
  3059. var internalFormat = this._getInternalFormat(format);
  3060. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3061. var needConversion = false;
  3062. if (internalFormat === gl.RGB) {
  3063. internalFormat = gl.RGBA;
  3064. needConversion = true;
  3065. }
  3066. var width = size;
  3067. var height = width;
  3068. texture.width = width;
  3069. texture.height = height;
  3070. // Double check on POT to generate Mips.
  3071. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3072. if (!isPot) {
  3073. generateMipMaps = false;
  3074. }
  3075. // Upload data if needed. The texture won't be ready until then.
  3076. if (data) {
  3077. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3078. }
  3079. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  3080. // Filters
  3081. if (data && generateMipMaps) {
  3082. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3083. }
  3084. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3087. }
  3088. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3089. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3091. }
  3092. else {
  3093. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3096. }
  3097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3099. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3100. return texture;
  3101. }
  3102. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3103. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  3104. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]),
  3105. onLoad: () => void = null,
  3106. onError: () => void = null,
  3107. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3108. invertY = false): InternalTexture {
  3109. var gl = this._gl;
  3110. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3111. scene._addPendingData(texture);
  3112. texture.url = url;
  3113. this._internalTexturesCache.push(texture);
  3114. var onerror = () => {
  3115. scene._removePendingData(texture);
  3116. if (onError) {
  3117. onError();
  3118. }
  3119. };
  3120. var internalCallback = (data) => {
  3121. var width = texture.width;
  3122. var height = texture.height;
  3123. var faceDataArrays = callback(data);
  3124. if (mipmmapGenerator) {
  3125. var textureType = this._getWebGLTextureType(type);
  3126. var internalFormat = this._getInternalFormat(format);
  3127. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3128. var needConversion = false;
  3129. if (internalFormat === gl.RGB) {
  3130. internalFormat = gl.RGBA;
  3131. needConversion = true;
  3132. }
  3133. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  3134. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3135. var mipData = mipmmapGenerator(faceDataArrays);
  3136. for (var level = 0; level < mipData.length; level++) {
  3137. var mipSize = width >> level;
  3138. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3139. let mipFaceData = mipData[level][faceIndex];
  3140. if (needConversion) {
  3141. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3142. }
  3143. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3144. }
  3145. }
  3146. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3147. }
  3148. else {
  3149. texture.generateMipMaps = !noMipmap;
  3150. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3151. }
  3152. texture.isReady = true;
  3153. this.resetTextureCache();
  3154. scene._removePendingData(texture);
  3155. if (onLoad) {
  3156. onLoad();
  3157. }
  3158. };
  3159. Tools.LoadFile(url, data => {
  3160. internalCallback(data);
  3161. }, onerror, scene.database, true);
  3162. return texture;
  3163. };
  3164. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Scene, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3165. var gl = this._gl;
  3166. if (!gl) {
  3167. return;
  3168. }
  3169. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3172. if (!noMipmap && !isCompressed) {
  3173. gl.generateMipmap(gl.TEXTURE_2D);
  3174. }
  3175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3176. this.resetTextureCache();
  3177. if (scene) {
  3178. scene._removePendingData(texture);
  3179. }
  3180. texture.onLoadedObservable.notifyObservers(texture);
  3181. texture.onLoadedObservable.clear();
  3182. }
  3183. private _prepareWebGLTexture(texture: InternalTexture, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3184. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3185. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3186. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3187. var gl = this._gl;
  3188. if (!gl) {
  3189. return;
  3190. }
  3191. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  3192. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3193. texture.baseWidth = width;
  3194. texture.baseHeight = height;
  3195. texture.width = potWidth;
  3196. texture.height = potHeight;
  3197. texture.isReady = true;
  3198. if (processFunction(potWidth, potHeight, () => {
  3199. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3200. })) {
  3201. // Returning as texture needs extra async steps
  3202. return;
  3203. }
  3204. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3205. }
  3206. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  3207. // Create new RGBA data container.
  3208. var rgbaData: ArrayBufferView;
  3209. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3210. rgbaData = new Float32Array(width * height * 4);
  3211. }
  3212. else {
  3213. rgbaData = new Uint32Array(width * height * 4);
  3214. }
  3215. // Convert each pixel.
  3216. for (let x = 0; x < width; x++) {
  3217. for (let y = 0; y < height; y++) {
  3218. let index = (y * width + x) * 3;
  3219. let newIndex = (y * width + x) * 4;
  3220. // Map Old Value to new value.
  3221. rgbaData[newIndex + 0] = rgbData[index + 0];
  3222. rgbaData[newIndex + 1] = rgbData[index + 1];
  3223. rgbaData[newIndex + 2] = rgbData[index + 2];
  3224. // Add fully opaque alpha channel.
  3225. rgbaData[newIndex + 3] = 1;
  3226. }
  3227. }
  3228. return rgbaData;
  3229. }
  3230. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3231. var gl = this._gl;
  3232. if (texture._framebuffer) {
  3233. gl.deleteFramebuffer(texture._framebuffer);
  3234. texture._framebuffer = null;
  3235. }
  3236. if (texture._depthStencilBuffer) {
  3237. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3238. texture._depthStencilBuffer = null;
  3239. }
  3240. if (texture._MSAAFramebuffer) {
  3241. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3242. texture._MSAAFramebuffer = null;
  3243. }
  3244. if (texture._MSAARenderBuffer) {
  3245. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3246. texture._MSAARenderBuffer = null;
  3247. }
  3248. }
  3249. public _releaseTexture(texture: InternalTexture): void {
  3250. var gl = this._gl;
  3251. this._releaseFramebufferObjects(texture);
  3252. gl.deleteTexture(texture._webGLTexture);
  3253. // Unbind channels
  3254. this.unbindAllTextures();
  3255. var index = this._internalTexturesCache.indexOf(texture);
  3256. if (index !== -1) {
  3257. this._internalTexturesCache.splice(index, 1);
  3258. }
  3259. // Integrated fixed lod samplers.
  3260. if (texture._lodTextureHigh) {
  3261. texture._lodTextureHigh.dispose();
  3262. }
  3263. if (texture._lodTextureMid) {
  3264. texture._lodTextureMid.dispose();
  3265. }
  3266. if (texture._lodTextureLow) {
  3267. texture._lodTextureLow.dispose();
  3268. }
  3269. }
  3270. private setProgram(program: WebGLProgram): void {
  3271. if (this._currentProgram !== program) {
  3272. this._gl.useProgram(program);
  3273. this._currentProgram = program;
  3274. }
  3275. }
  3276. public bindSamplers(effect: Effect): void {
  3277. this.setProgram(effect.getProgram());
  3278. var samplers = effect.getSamplers();
  3279. for (var index = 0; index < samplers.length; index++) {
  3280. var uniform = effect.getUniform(samplers[index]);
  3281. this._gl.uniform1i(uniform, index);
  3282. }
  3283. this._currentEffect = null;
  3284. }
  3285. private activateTexture(texture: number): void {
  3286. if (this._activeTexture !== texture) {
  3287. this._gl.activeTexture(texture);
  3288. this._activeTexture = texture;
  3289. }
  3290. }
  3291. public _bindTextureDirectly(target: number, texture: InternalTexture): void {
  3292. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  3293. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3294. this._activeTexturesCache[this._activeTexture] = texture;
  3295. }
  3296. }
  3297. public _bindTexture(channel: number, texture: InternalTexture): void {
  3298. if (channel < 0) {
  3299. return;
  3300. }
  3301. this.activateTexture(this._gl.TEXTURE0 + channel);
  3302. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3303. }
  3304. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  3305. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3306. }
  3307. public unbindAllTextures(): void {
  3308. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3309. this.activateTexture(this._gl["TEXTURE" + channel]);
  3310. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3311. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3312. }
  3313. }
  3314. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  3315. if (channel < 0) {
  3316. return;
  3317. }
  3318. this._gl.uniform1i(uniform, channel);
  3319. this._setTexture(channel, texture);
  3320. }
  3321. private _setTexture(channel: number, texture: BaseTexture): void {
  3322. // Not ready?
  3323. if (!texture) {
  3324. if (this._activeTexturesCache[channel] != null) {
  3325. this.activateTexture(this._gl["TEXTURE" + channel]);
  3326. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3327. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3328. }
  3329. return;
  3330. }
  3331. // Video
  3332. var alreadyActivated = false;
  3333. if ((<VideoTexture>texture).video) {
  3334. this.activateTexture(this._gl["TEXTURE" + channel]);
  3335. alreadyActivated = true;
  3336. (<VideoTexture>texture).update();
  3337. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3338. texture.delayLoad();
  3339. return;
  3340. }
  3341. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  3342. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  3343. if (this._activeTexturesCache[channel] === internalTexture) {
  3344. return;
  3345. }
  3346. if (!alreadyActivated) {
  3347. this.activateTexture(this._gl["TEXTURE" + channel]);
  3348. }
  3349. if (internalTexture.isCube) {
  3350. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3351. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3352. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3353. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3354. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3355. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3356. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3357. }
  3358. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3359. } else {
  3360. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  3361. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3362. internalTexture._cachedWrapU = texture.wrapU;
  3363. switch (texture.wrapU) {
  3364. case Texture.WRAP_ADDRESSMODE:
  3365. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3366. break;
  3367. case Texture.CLAMP_ADDRESSMODE:
  3368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3369. break;
  3370. case Texture.MIRROR_ADDRESSMODE:
  3371. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3372. break;
  3373. }
  3374. }
  3375. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3376. internalTexture._cachedWrapV = texture.wrapV;
  3377. switch (texture.wrapV) {
  3378. case Texture.WRAP_ADDRESSMODE:
  3379. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3380. break;
  3381. case Texture.CLAMP_ADDRESSMODE:
  3382. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3383. break;
  3384. case Texture.MIRROR_ADDRESSMODE:
  3385. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3386. break;
  3387. }
  3388. }
  3389. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3390. }
  3391. }
  3392. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  3393. if (channel < 0) {
  3394. return;
  3395. }
  3396. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3397. this._textureUnits = new Int32Array(textures.length);
  3398. }
  3399. for (let i = 0; i < textures.length; i++) {
  3400. this._textureUnits[i] = channel + i;
  3401. }
  3402. this._gl.uniform1iv(uniform, this._textureUnits);
  3403. for (var index = 0; index < textures.length; index++) {
  3404. this._setTexture(channel + index, textures[index]);
  3405. }
  3406. }
  3407. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  3408. var internalTexture = texture.getInternalTexture();
  3409. if (!internalTexture) {
  3410. return;
  3411. }
  3412. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3413. var value = texture.anisotropicFilteringLevel;
  3414. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  3415. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  3416. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  3417. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  3418. }
  3419. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  3420. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  3421. internalTexture._cachedAnisotropicFilteringLevel = value;
  3422. }
  3423. }
  3424. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  3425. var data = new Uint8Array(height * width * 4);
  3426. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3427. return data;
  3428. }
  3429. /**
  3430. * Add an externaly attached data from its key.
  3431. * This method call will fail and return false, if such key already exists.
  3432. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3433. * @param key the unique key that identifies the data
  3434. * @param data the data object to associate to the key for this Engine instance
  3435. * @return true if no such key were already present and the data was added successfully, false otherwise
  3436. */
  3437. public addExternalData<T>(key: string, data: T): boolean {
  3438. if (!this._externalData) {
  3439. this._externalData = new StringDictionary<Object>();
  3440. }
  3441. return this._externalData.add(key, data);
  3442. }
  3443. /**
  3444. * Get an externaly attached data from its key
  3445. * @param key the unique key that identifies the data
  3446. * @return the associated data, if present (can be null), or undefined if not present
  3447. */
  3448. public getExternalData<T>(key: string): T {
  3449. if (!this._externalData) {
  3450. this._externalData = new StringDictionary<Object>();
  3451. }
  3452. return <T>this._externalData.get(key);
  3453. }
  3454. /**
  3455. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3456. * @param key the unique key that identifies the data
  3457. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3458. * @return the associated data, can be null if the factory returned null.
  3459. */
  3460. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3461. if (!this._externalData) {
  3462. this._externalData = new StringDictionary<Object>();
  3463. }
  3464. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3465. }
  3466. /**
  3467. * Remove an externaly attached data from the Engine instance
  3468. * @param key the unique key that identifies the data
  3469. * @return true if the data was successfully removed, false if it doesn't exist
  3470. */
  3471. public removeExternalData(key): boolean {
  3472. if (!this._externalData) {
  3473. this._externalData = new StringDictionary<Object>();
  3474. }
  3475. return this._externalData.remove(key);
  3476. }
  3477. public unbindAllAttributes() {
  3478. if (this._mustWipeVertexAttributes) {
  3479. this._mustWipeVertexAttributes = false;
  3480. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3481. this._gl.disableVertexAttribArray(i);
  3482. this._vertexAttribArraysEnabled[i] = false;
  3483. this._currentBufferPointers[i].active = false;
  3484. }
  3485. return;
  3486. }
  3487. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3488. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3489. continue;
  3490. }
  3491. this._gl.disableVertexAttribArray(i);
  3492. this._vertexAttribArraysEnabled[i] = false;
  3493. this._currentBufferPointers[i].active = false;
  3494. }
  3495. }
  3496. public releaseEffects() {
  3497. for (var name in this._compiledEffects) {
  3498. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3499. }
  3500. this._compiledEffects = {};
  3501. }
  3502. // Dispose
  3503. public dispose(): void {
  3504. this.hideLoadingUI();
  3505. this.stopRenderLoop();
  3506. // Release postProcesses
  3507. while (this.postProcesses.length) {
  3508. this.postProcesses[0].dispose();
  3509. }
  3510. // Empty texture
  3511. if (this._emptyTexture) {
  3512. this._releaseTexture(this._emptyTexture);
  3513. this._emptyTexture = null;
  3514. }
  3515. if (this._emptyCubeTexture) {
  3516. this._releaseTexture(this._emptyCubeTexture);
  3517. this._emptyCubeTexture = null;
  3518. }
  3519. // Rescale PP
  3520. if (this._rescalePostProcess) {
  3521. this._rescalePostProcess.dispose();
  3522. }
  3523. // Release scenes
  3524. while (this.scenes.length) {
  3525. this.scenes[0].dispose();
  3526. }
  3527. // Release audio engine
  3528. if (Engine.audioEngine) {
  3529. Engine.audioEngine.dispose();
  3530. }
  3531. // Release effects
  3532. this.releaseEffects();
  3533. // Unbind
  3534. this.unbindAllAttributes();
  3535. if (this._dummyFramebuffer) {
  3536. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3537. }
  3538. this._gl = null;
  3539. //WebVR
  3540. this.disableVR();
  3541. // Events
  3542. window.removeEventListener("blur", this._onBlur);
  3543. window.removeEventListener("focus", this._onFocus);
  3544. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  3545. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  3546. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  3547. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  3548. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  3549. if (!this._doNotHandleContextLost) {
  3550. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3551. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3552. }
  3553. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3554. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3555. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3556. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3557. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3558. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3559. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3560. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3561. // Remove from Instances
  3562. var index = Engine.Instances.indexOf(this);
  3563. if (index >= 0) {
  3564. Engine.Instances.splice(index, 1);
  3565. }
  3566. this._workingCanvas = null;
  3567. this._workingContext = null;
  3568. this._currentBufferPointers = null;
  3569. this._renderingCanvas = null;
  3570. this._currentProgram = null;
  3571. this.onResizeObservable.clear();
  3572. this.onCanvasBlurObservable.clear();
  3573. this.onCanvasFocusObservable.clear();
  3574. this.onCanvasPointerOutObservable.clear();
  3575. BABYLON.Effect.ResetCache();
  3576. }
  3577. // Loading screen
  3578. public displayLoadingUI(): void {
  3579. const loadingScreen = this.loadingScreen;
  3580. if (loadingScreen) {
  3581. loadingScreen.displayLoadingUI();
  3582. }
  3583. }
  3584. public hideLoadingUI(): void {
  3585. const loadingScreen = this.loadingScreen;
  3586. if (loadingScreen) {
  3587. loadingScreen.hideLoadingUI();
  3588. }
  3589. }
  3590. public get loadingScreen(): ILoadingScreen {
  3591. if (!this._loadingScreen && DefaultLoadingScreen)
  3592. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  3593. return this._loadingScreen;
  3594. }
  3595. public set loadingScreen(loadingScreen: ILoadingScreen) {
  3596. this._loadingScreen = loadingScreen;
  3597. }
  3598. public set loadingUIText(text: string) {
  3599. this.loadingScreen.loadingUIText = text;
  3600. }
  3601. public set loadingUIBackgroundColor(color: string) {
  3602. this.loadingScreen.loadingUIBackgroundColor = color;
  3603. }
  3604. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3605. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  3606. }
  3607. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3608. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  3609. }
  3610. public getVertexShaderSource(program: WebGLProgram): string {
  3611. var shaders = this._gl.getAttachedShaders(program);
  3612. return this._gl.getShaderSource(shaders[0]);
  3613. }
  3614. public getFragmentShaderSource(program: WebGLProgram): string {
  3615. var shaders = this._gl.getAttachedShaders(program);
  3616. return this._gl.getShaderSource(shaders[1]);
  3617. }
  3618. public getError(): number {
  3619. return this._gl.getError();
  3620. }
  3621. // FPS
  3622. public getFps(): number {
  3623. return this._fps;
  3624. }
  3625. public getDeltaTime(): number {
  3626. return this._deltaTime;
  3627. }
  3628. private _measureFps(): void {
  3629. this._performanceMonitor.sampleFrame();
  3630. this._fps = this._performanceMonitor.averageFPS;
  3631. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  3632. }
  3633. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  3634. let gl = this._gl;
  3635. if (!this._dummyFramebuffer) {
  3636. this._dummyFramebuffer = gl.createFramebuffer();
  3637. }
  3638. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  3639. if (faceIndex > -1) {
  3640. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  3641. } else {
  3642. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3643. }
  3644. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  3645. let buffer: ArrayBufferView;
  3646. switch (readType) {
  3647. case gl.UNSIGNED_BYTE:
  3648. buffer = new Uint8Array(4 * width * height);
  3649. readType = gl.UNSIGNED_BYTE;
  3650. break;
  3651. default:
  3652. buffer = new Float32Array(4 * width * height);
  3653. readType = gl.FLOAT;
  3654. break;
  3655. }
  3656. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  3657. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  3658. return buffer;
  3659. }
  3660. private _canRenderToFloatFramebuffer(): boolean {
  3661. if (this._webGLVersion > 1) {
  3662. return this._caps.colorBufferFloat;
  3663. }
  3664. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  3665. }
  3666. private _canRenderToHalfFloatFramebuffer(): boolean {
  3667. if (this._webGLVersion > 1) {
  3668. return this._caps.colorBufferFloat;
  3669. }
  3670. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  3671. }
  3672. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3673. private _canRenderToFramebuffer(type: number): boolean {
  3674. let gl = this._gl;
  3675. //clear existing errors
  3676. while (gl.getError() !== gl.NO_ERROR) { }
  3677. let successful = true;
  3678. let texture = gl.createTexture();
  3679. gl.bindTexture(gl.TEXTURE_2D, texture);
  3680. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3683. let fb = gl.createFramebuffer();
  3684. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3685. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3686. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3687. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3688. successful = successful && (gl.getError() === gl.NO_ERROR);
  3689. //try render by clearing frame buffer's color buffer
  3690. if (successful) {
  3691. gl.clear(gl.COLOR_BUFFER_BIT);
  3692. successful = successful && (gl.getError() === gl.NO_ERROR);
  3693. }
  3694. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3695. if (successful) {
  3696. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3697. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3698. let readFormat = gl.RGBA;
  3699. let readType = gl.UNSIGNED_BYTE;
  3700. let buffer = new Uint8Array(4);
  3701. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3702. successful = successful && (gl.getError() === gl.NO_ERROR);
  3703. }
  3704. //clean up
  3705. gl.deleteTexture(texture);
  3706. gl.deleteFramebuffer(fb);
  3707. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3708. //clear accumulated errors
  3709. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3710. return successful;
  3711. }
  3712. public _getWebGLTextureType(type: number): number {
  3713. if (type === Engine.TEXTURETYPE_FLOAT) {
  3714. return this._gl.FLOAT;
  3715. }
  3716. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3717. // Add Half Float Constant.
  3718. return this._gl.HALF_FLOAT_OES;
  3719. }
  3720. return this._gl.UNSIGNED_BYTE;
  3721. };
  3722. public _getRGBABufferInternalSizedFormat(type: number): number {
  3723. if (this._webGLVersion === 1) {
  3724. return this._gl.RGBA;
  3725. }
  3726. if (type === Engine.TEXTURETYPE_FLOAT) {
  3727. return this._gl.RGBA32F;
  3728. }
  3729. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3730. return this._gl.RGBA16F;
  3731. }
  3732. return this._gl.RGBA;
  3733. };
  3734. public createQuery(): WebGLQuery {
  3735. return this._gl.createQuery();
  3736. }
  3737. public deleteQuery(query: WebGLQuery): Engine {
  3738. this._gl.deleteQuery(query);
  3739. return this;
  3740. }
  3741. public isQueryResultAvailable(query: WebGLQuery): boolean {
  3742. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  3743. }
  3744. public getQueryResult(query: WebGLQuery): number {
  3745. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  3746. }
  3747. public beginQuery(algorithmType: number, query: WebGLQuery) {
  3748. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3749. this._gl.beginQuery(glAlgorithm, query);
  3750. }
  3751. public endQuery(algorithmType: number): Engine {
  3752. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3753. this._gl.endQuery(glAlgorithm);
  3754. return this;
  3755. }
  3756. private getGlAlgorithmType(algorithmType: number): number {
  3757. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  3758. }
  3759. // Statics
  3760. public static isSupported(): boolean {
  3761. try {
  3762. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  3763. if (navigator.isCocoonJS) {
  3764. return true;
  3765. }
  3766. var tempcanvas = document.createElement("canvas");
  3767. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3768. return gl != null && !!window.WebGLRenderingContext;
  3769. } catch (e) {
  3770. return false;
  3771. }
  3772. }
  3773. }
  3774. }