babylon.engine.ts 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379
  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. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  15. magFilter = gl.LINEAR;
  16. if (generateMipMaps) {
  17. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  18. } else {
  19. minFilter = gl.LINEAR;
  20. }
  21. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  22. magFilter = gl.LINEAR;
  23. if (generateMipMaps) {
  24. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  25. } else {
  26. minFilter = gl.LINEAR;
  27. }
  28. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  29. magFilter = gl.NEAREST;
  30. if (generateMipMaps) {
  31. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  32. } else {
  33. minFilter = gl.NEAREST;
  34. }
  35. }
  36. return {
  37. min: minFilter,
  38. mag: magFilter
  39. }
  40. }
  41. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  42. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  43. var engine = scene.getEngine();
  44. var potWidth = Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  45. var potHeight = Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  46. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  47. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  48. texture._baseWidth = width;
  49. texture._baseHeight = height;
  50. texture._width = potWidth;
  51. texture._height = potHeight;
  52. texture.isReady = true;
  53. processFunction(potWidth, potHeight);
  54. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  55. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  56. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  57. if (!noMipmap && !isCompressed) {
  58. gl.generateMipmap(gl.TEXTURE_2D);
  59. }
  60. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  61. engine.resetTextureCache();
  62. scene._removePendingData(texture);
  63. texture.onLoadedCallbacks.forEach(callback => {
  64. callback();
  65. });
  66. texture.onLoadedCallbacks = [];
  67. };
  68. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  69. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  70. var img: HTMLImageElement;
  71. var onload = () => {
  72. loadedImages[index] = img;
  73. loadedImages._internalCount++;
  74. scene._removePendingData(img);
  75. if (loadedImages._internalCount === 6) {
  76. onfinish(loadedImages);
  77. }
  78. };
  79. var onerror = () => {
  80. scene._removePendingData(img);
  81. if (onErrorCallBack) {
  82. onErrorCallBack();
  83. }
  84. };
  85. img = Tools.LoadImage(url, onload, onerror, scene.database);
  86. scene._addPendingData(img);
  87. }
  88. var cascadeLoad = (rootUrl: string, scene,
  89. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  90. var loadedImages: any = [];
  91. loadedImages._internalCount = 0;
  92. for (var index = 0; index < 6; index++) {
  93. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  94. }
  95. };
  96. export class InstancingAttributeInfo {
  97. /**
  98. * Index/offset of the attribute in the vertex shader
  99. */
  100. index: number;
  101. /**
  102. * size of the attribute, 1, 2, 3 or 4
  103. */
  104. attributeSize: number;
  105. /**
  106. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  107. * default is FLOAT
  108. */
  109. attribyteType: number;
  110. /**
  111. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  112. */
  113. normalized: boolean;
  114. /**
  115. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  116. */
  117. offset: number;
  118. /**
  119. * Name of the GLSL attribute, for debugging purpose only
  120. */
  121. attributeName: string;
  122. }
  123. export class EngineCapabilities {
  124. public maxTexturesImageUnits: number;
  125. public maxTextureSize: number;
  126. public maxCubemapTextureSize: number;
  127. public maxRenderTextureSize: number;
  128. public maxVertexAttribs: number;
  129. public maxVaryingVectors: number;
  130. public maxVertexUniformVectors: number;
  131. public maxFragmentUniformVectors: number;
  132. public standardDerivatives: boolean;
  133. public s3tc: WEBGL_compressed_texture_s3tc;
  134. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  135. public etc1: any; //WEBGL_compressed_texture_etc1;
  136. public etc2: any; //WEBGL_compressed_texture_etc;
  137. public astc: any; //WEBGL_compressed_texture_astc;
  138. public atc: any; //WEBGL_compressed_texture_atc;
  139. public textureFloat: boolean;
  140. public vertexArrayObject: boolean;
  141. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  142. public maxAnisotropy: number;
  143. public instancedArrays: boolean;
  144. public uintIndices: boolean;
  145. public highPrecisionShaderSupported: boolean;
  146. public fragmentDepthSupported: boolean;
  147. public textureFloatLinearFiltering: boolean;
  148. public textureFloatRender: boolean;
  149. public textureHalfFloat: boolean;
  150. public textureHalfFloatLinearFiltering: boolean;
  151. public textureHalfFloatRender: boolean;
  152. public textureLOD: boolean;
  153. public drawBuffersExtension;
  154. public colorBufferFloat: boolean;
  155. }
  156. export interface EngineOptions extends WebGLContextAttributes {
  157. limitDeviceRatio?: number;
  158. autoEnableWebVR?: boolean;
  159. disableWebGL2Support?: boolean;
  160. }
  161. /**
  162. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  163. */
  164. export class Engine {
  165. // Const statics
  166. private static _ALPHA_DISABLE = 0;
  167. private static _ALPHA_ADD = 1;
  168. private static _ALPHA_COMBINE = 2;
  169. private static _ALPHA_SUBTRACT = 3;
  170. private static _ALPHA_MULTIPLY = 4;
  171. private static _ALPHA_MAXIMIZED = 5;
  172. private static _ALPHA_ONEONE = 6;
  173. private static _ALPHA_PREMULTIPLIED = 7;
  174. private static _DELAYLOADSTATE_NONE = 0;
  175. private static _DELAYLOADSTATE_LOADED = 1;
  176. private static _DELAYLOADSTATE_LOADING = 2;
  177. private static _DELAYLOADSTATE_NOTLOADED = 4;
  178. private static _TEXTUREFORMAT_ALPHA = 0;
  179. private static _TEXTUREFORMAT_LUMINANCE = 1;
  180. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  181. private static _TEXTUREFORMAT_RGB = 4;
  182. private static _TEXTUREFORMAT_RGBA = 5;
  183. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  184. private static _TEXTURETYPE_FLOAT = 1;
  185. private static _TEXTURETYPE_HALF_FLOAT = 2;
  186. // Depht or Stencil test Constants.
  187. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  188. 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.
  189. 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.
  190. 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.
  191. 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.
  192. 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.
  193. 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.
  194. 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.
  195. private static HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  196. private static RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  197. private static RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  198. public static get NEVER(): number {
  199. return Engine._NEVER;
  200. }
  201. public static get ALWAYS(): number {
  202. return Engine._ALWAYS;
  203. }
  204. public static get LESS(): number {
  205. return Engine._LESS;
  206. }
  207. public static get EQUAL(): number {
  208. return Engine._EQUAL;
  209. }
  210. public static get LEQUAL(): number {
  211. return Engine._LEQUAL;
  212. }
  213. public static get GREATER(): number {
  214. return Engine._GREATER;
  215. }
  216. public static get GEQUAL(): number {
  217. return Engine._GEQUAL;
  218. }
  219. public static get NOTEQUAL(): number {
  220. return Engine._NOTEQUAL;
  221. }
  222. // Stencil Actions Constants.
  223. private static _KEEP = 0x1E00;
  224. private static _REPLACE = 0x1E01;
  225. private static _INCR = 0x1E02;
  226. private static _DECR = 0x1E03;
  227. private static _INVERT = 0x150A;
  228. private static _INCR_WRAP = 0x8507;
  229. private static _DECR_WRAP = 0x8508;
  230. public static get KEEP(): number {
  231. return Engine._KEEP;
  232. }
  233. public static get REPLACE(): number {
  234. return Engine._REPLACE;
  235. }
  236. public static get INCR(): number {
  237. return Engine._INCR;
  238. }
  239. public static get DECR(): number {
  240. return Engine._DECR;
  241. }
  242. public static get INVERT(): number {
  243. return Engine._INVERT;
  244. }
  245. public static get INCR_WRAP(): number {
  246. return Engine._INCR_WRAP;
  247. }
  248. public static get DECR_WRAP(): number {
  249. return Engine._DECR_WRAP;
  250. }
  251. public static get ALPHA_DISABLE(): number {
  252. return Engine._ALPHA_DISABLE;
  253. }
  254. public static get ALPHA_ONEONE(): number {
  255. return Engine._ALPHA_ONEONE;
  256. }
  257. public static get ALPHA_ADD(): number {
  258. return Engine._ALPHA_ADD;
  259. }
  260. public static get ALPHA_COMBINE(): number {
  261. return Engine._ALPHA_COMBINE;
  262. }
  263. public static get ALPHA_SUBTRACT(): number {
  264. return Engine._ALPHA_SUBTRACT;
  265. }
  266. public static get ALPHA_MULTIPLY(): number {
  267. return Engine._ALPHA_MULTIPLY;
  268. }
  269. public static get ALPHA_MAXIMIZED(): number {
  270. return Engine._ALPHA_MAXIMIZED;
  271. }
  272. public static get ALPHA_PREMULTIPLIED(): number {
  273. return Engine._ALPHA_PREMULTIPLIED;
  274. }
  275. public static get DELAYLOADSTATE_NONE(): number {
  276. return Engine._DELAYLOADSTATE_NONE;
  277. }
  278. public static get DELAYLOADSTATE_LOADED(): number {
  279. return Engine._DELAYLOADSTATE_LOADED;
  280. }
  281. public static get DELAYLOADSTATE_LOADING(): number {
  282. return Engine._DELAYLOADSTATE_LOADING;
  283. }
  284. public static get DELAYLOADSTATE_NOTLOADED(): number {
  285. return Engine._DELAYLOADSTATE_NOTLOADED;
  286. }
  287. public static get TEXTUREFORMAT_ALPHA(): number {
  288. return Engine._TEXTUREFORMAT_ALPHA;
  289. }
  290. public static get TEXTUREFORMAT_LUMINANCE(): number {
  291. return Engine._TEXTUREFORMAT_LUMINANCE;
  292. }
  293. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  294. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  295. }
  296. public static get TEXTUREFORMAT_RGB(): number {
  297. return Engine._TEXTUREFORMAT_RGB;
  298. }
  299. public static get TEXTUREFORMAT_RGBA(): number {
  300. return Engine._TEXTUREFORMAT_RGBA;
  301. }
  302. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  303. return Engine._TEXTURETYPE_UNSIGNED_INT;
  304. }
  305. public static get TEXTURETYPE_FLOAT(): number {
  306. return Engine._TEXTURETYPE_FLOAT;
  307. }
  308. public static get TEXTURETYPE_HALF_FLOAT(): number {
  309. return Engine._TEXTURETYPE_HALF_FLOAT;
  310. }
  311. public static get Version(): string {
  312. return "2.6-alpha";
  313. }
  314. // Updatable statics so stick with vars here
  315. public static CollisionsEpsilon = 0.001;
  316. public static CodeRepository = "src/";
  317. public static ShadersRepository = "src/Shaders/";
  318. // Public members
  319. public isFullscreen = false;
  320. public isPointerLock = false;
  321. public cullBackFaces = true;
  322. public renderEvenInBackground = true;
  323. // To enable/disable IDB support and avoid XHR on .manifest
  324. public enableOfflineSupport = true;
  325. public scenes = new Array<Scene>();
  326. //WebVR
  327. //The new WebVR uses promises.
  328. //this promise resolves with the current devices available.
  329. public vrDisplaysPromise;
  330. private _vrDisplays;
  331. private _vrDisplayEnabled;
  332. private _oldSize: BABYLON.Size;
  333. private _oldHardwareScaleFactor: number;
  334. private _vrAnimationFrameHandler: number;
  335. // Private Members
  336. public _gl: WebGLRenderingContext;
  337. private _renderingCanvas: HTMLCanvasElement;
  338. private _windowIsBackground = false;
  339. private _webGLVersion = 1.0;
  340. private _badOS = false;
  341. public static audioEngine: AudioEngine;
  342. private _onBlur: () => void;
  343. private _onFocus: () => void;
  344. private _onFullscreenChange: () => void;
  345. private _onPointerLockChange: () => void;
  346. private _hardwareScalingLevel: number;
  347. private _caps: EngineCapabilities;
  348. private _pointerLockRequested: boolean;
  349. private _alphaTest: boolean;
  350. private _isStencilEnable: boolean;
  351. private _loadingScreen: ILoadingScreen;
  352. public _drawCalls = new PerfCounter();
  353. private _glVersion: string;
  354. private _glRenderer: string;
  355. private _glVendor: string;
  356. private _videoTextureSupported: boolean;
  357. private _renderingQueueLaunched = false;
  358. private _activeRenderLoops = [];
  359. // FPS
  360. private fpsRange = 60;
  361. private previousFramesDuration = [];
  362. private fps = 60;
  363. private deltaTime = 0;
  364. // States
  365. private _depthCullingState = new Internals._DepthCullingState();
  366. private _stencilState = new Internals._StencilState();
  367. private _alphaState = new Internals._AlphaState();
  368. private _alphaMode = Engine.ALPHA_DISABLE;
  369. // Cache
  370. private _loadedTexturesCache = new Array<WebGLTexture>();
  371. private _maxTextureChannels = 16;
  372. private _activeTexture: number;
  373. private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
  374. private _currentEffect: Effect;
  375. private _currentProgram: WebGLProgram;
  376. private _compiledEffects = {};
  377. private _vertexAttribArraysEnabled: boolean[] = [];
  378. private _cachedViewport: Viewport;
  379. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  380. private _cachedVertexBuffers: any;
  381. private _cachedIndexBuffer: WebGLBuffer;
  382. private _cachedEffectForVertexBuffers: Effect;
  383. private _currentRenderTarget: WebGLTexture;
  384. private _uintIndicesCurrentlySet = false;
  385. private _currentBoundBuffer = new Array<WebGLBuffer>();
  386. private _currentFramebuffer: WebGLFramebuffer;
  387. private _currentBufferPointers: Array<{ indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number, buffer: WebGLBuffer }> = [];
  388. private _currentInstanceLocations = new Array<number>();
  389. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  390. private _textureUnits: Int32Array;
  391. private _workingCanvas: HTMLCanvasElement;
  392. private _workingContext: CanvasRenderingContext2D;
  393. private _externalData: StringDictionary<Object>;
  394. private _bindedRenderFunction: any;
  395. private _vaoRecordInProgress = false;
  396. private _mustWipeVertexAttributes = false;
  397. // Hardware supported Compressed Textures
  398. private _texturesSupported = new Array<string>();
  399. private _textureFormatInUse : string;
  400. public get texturesSupported(): Array<string> {
  401. return this._texturesSupported;
  402. }
  403. public get textureFormatInUse(): string {
  404. return this._textureFormatInUse;
  405. }
  406. /**
  407. * @constructor
  408. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  409. * @param {boolean} [antialias] - enable antialias
  410. * @param options - further options to be sent to the getContext function
  411. */
  412. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  413. this._renderingCanvas = canvas;
  414. this._externalData = new StringDictionary<Object>();
  415. options = options || {};
  416. if (antialias != null) {
  417. options.antialias = antialias;
  418. }
  419. if (options.preserveDrawingBuffer === undefined) {
  420. options.preserveDrawingBuffer = false;
  421. }
  422. // GL
  423. if (!options.disableWebGL2Support) {
  424. try {
  425. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  426. if (this._gl) {
  427. this._webGLVersion = 2.0;
  428. }
  429. } catch (e) {
  430. // Do nothing
  431. }
  432. }
  433. if (!this._gl) {
  434. if (!canvas) {
  435. throw new Error("The provided canvas is null or undefined.");
  436. }
  437. try {
  438. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  439. } catch (e) {
  440. throw new Error("WebGL not supported");
  441. }
  442. }
  443. if (!this._gl) {
  444. throw new Error("WebGL not supported");
  445. }
  446. this._onBlur = () => {
  447. this._windowIsBackground = true;
  448. };
  449. this._onFocus = () => {
  450. this._windowIsBackground = false;
  451. };
  452. window.addEventListener("blur", this._onBlur);
  453. window.addEventListener("focus", this._onFocus);
  454. // Viewport
  455. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  456. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  457. this.resize();
  458. // Caps
  459. this._isStencilEnable = options.stencil;
  460. this._caps = new EngineCapabilities();
  461. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  462. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  463. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  464. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  465. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  466. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  467. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  468. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  469. // Infos
  470. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  471. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  472. if (rendererInfo != null) {
  473. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  474. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  475. }
  476. if (!this._glVendor) {
  477. this._glVendor = "Unknown vendor";
  478. }
  479. if (!this._glRenderer) {
  480. this._glRenderer = "Unknown renderer";
  481. }
  482. // Extensions
  483. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  484. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc' );
  485. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc' );
  486. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  487. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1' );
  488. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc' ) ||
  489. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  490. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc' ) || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc' );
  491. 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');
  492. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  493. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  494. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  495. this._caps.highPrecisionShaderSupported = true;
  496. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  497. // Checks if some of the format renders first to allow the use of webgl inspector.
  498. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float')
  499. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  500. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  501. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  502. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  503. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  504. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  505. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  506. // Vertex array object
  507. if ( this._webGLVersion > 1) {
  508. this._caps.vertexArrayObject = true;
  509. } else{
  510. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  511. if (vertexArrayObjectExtension != null) {
  512. this._caps.vertexArrayObject = true;
  513. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  514. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  515. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  516. } else{
  517. this._caps.vertexArrayObject = false;
  518. }
  519. }
  520. // Instances count
  521. if ( this._webGLVersion > 1) {
  522. this._caps.instancedArrays = true;
  523. } else{
  524. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  525. if (instanceExtension != null) {
  526. this._caps.instancedArrays = true;
  527. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  528. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  529. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  530. } else{
  531. this._caps.instancedArrays = false;
  532. }
  533. }
  534. // Intelligently add supported compressed formats in order to check for.
  535. // Check for ASTC support first as it is most powerful and to be very cross platform.
  536. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  537. // Likely no hardware which supports both PVR & DXT, so order matters little.
  538. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  539. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  540. if (this._caps.astc ) this.texturesSupported.push('-astc.ktx');
  541. if (this._caps.s3tc ) this.texturesSupported.push('-dxt.ktx');
  542. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  543. if (this._caps.etc2 ) this.texturesSupported.push('-etc2.ktx');
  544. if (this._caps.atc ) this.texturesSupported.push('-atc.ktx');
  545. if (this._caps.etc1 ) this.texturesSupported.push('-etc1.ktx');
  546. if (this._gl.getShaderPrecisionFormat) {
  547. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  548. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  549. }
  550. // Depth buffer
  551. this.setDepthBuffer(true);
  552. this.setDepthFunctionToLessOrEqual();
  553. this.setDepthWrite(true);
  554. // Fullscreen
  555. this._onFullscreenChange = () => {
  556. if (document.fullscreen !== undefined) {
  557. this.isFullscreen = document.fullscreen;
  558. } else if (document.mozFullScreen !== undefined) {
  559. this.isFullscreen = document.mozFullScreen;
  560. } else if (document.webkitIsFullScreen !== undefined) {
  561. this.isFullscreen = document.webkitIsFullScreen;
  562. } else if (document.msIsFullScreen !== undefined) {
  563. this.isFullscreen = document.msIsFullScreen;
  564. }
  565. // Pointer lock
  566. if (this.isFullscreen && this._pointerLockRequested) {
  567. canvas.requestPointerLock = canvas.requestPointerLock ||
  568. canvas.msRequestPointerLock ||
  569. canvas.mozRequestPointerLock ||
  570. canvas.webkitRequestPointerLock;
  571. if (canvas.requestPointerLock) {
  572. canvas.requestPointerLock();
  573. }
  574. }
  575. };
  576. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  577. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  578. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  579. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  580. // Pointer lock
  581. this._onPointerLockChange = () => {
  582. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  583. document.webkitPointerLockElement === canvas ||
  584. document.msPointerLockElement === canvas ||
  585. document.pointerLockElement === canvas
  586. );
  587. };
  588. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  589. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  590. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  591. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  592. if (AudioEngine && !Engine.audioEngine) {
  593. Engine.audioEngine = new AudioEngine();
  594. }
  595. //default loading screen
  596. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  597. //Load WebVR Devices
  598. if (options.autoEnableWebVR) {
  599. this.initWebVR();
  600. }
  601. //Detect if we are running on a faulty buggy OS.
  602. var regexp = /AppleWebKit.*10.[\d] Mobile/
  603. //ua sniffing is the tool of the devil.
  604. this._badOS = regexp.test(navigator.userAgent);
  605. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  606. }
  607. public get webGLVersion(): number {
  608. return this._webGLVersion;
  609. }
  610. /**
  611. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  612. */
  613. public get isStencilEnable(): boolean {
  614. return this._isStencilEnable;
  615. }
  616. private _prepareWorkingCanvas(): void {
  617. if (this._workingCanvas) {
  618. return;
  619. }
  620. this._workingCanvas = document.createElement("canvas");
  621. this._workingContext = this._workingCanvas.getContext("2d");
  622. }
  623. public resetTextureCache() {
  624. for (var index = 0; index < this._maxTextureChannels; index++) {
  625. this._activeTexturesCache[index] = null;
  626. }
  627. }
  628. public getGlInfo() {
  629. return {
  630. vendor: this._glVendor,
  631. renderer: this._glRenderer,
  632. version: this._glVersion
  633. }
  634. }
  635. public getAspectRatio(camera: Camera, useScreen = false): number {
  636. var viewport = camera.viewport;
  637. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  638. }
  639. public getRenderWidth(useScreen = false): number {
  640. if (!useScreen && this._currentRenderTarget) {
  641. return this._currentRenderTarget._width;
  642. }
  643. return this._renderingCanvas.width;
  644. }
  645. public getRenderHeight(useScreen = false): number {
  646. if (!useScreen && this._currentRenderTarget) {
  647. return this._currentRenderTarget._height;
  648. }
  649. return this._renderingCanvas.height;
  650. }
  651. public getRenderingCanvas(): HTMLCanvasElement {
  652. return this._renderingCanvas;
  653. }
  654. public getRenderingCanvasClientRect(): ClientRect {
  655. return this._renderingCanvas.getBoundingClientRect();
  656. }
  657. public setHardwareScalingLevel(level: number): void {
  658. this._hardwareScalingLevel = level;
  659. this.resize();
  660. }
  661. public getHardwareScalingLevel(): number {
  662. return this._hardwareScalingLevel;
  663. }
  664. public getLoadedTexturesCache(): WebGLTexture[] {
  665. return this._loadedTexturesCache;
  666. }
  667. public getCaps(): EngineCapabilities {
  668. return this._caps;
  669. }
  670. public get drawCalls(): number {
  671. return this._drawCalls.current;
  672. }
  673. public get drawCallsPerfCounter(): PerfCounter {
  674. return this._drawCalls;
  675. }
  676. public getDepthFunction(): number {
  677. return this._depthCullingState.depthFunc;
  678. }
  679. public setDepthFunction(depthFunc: number) {
  680. this._depthCullingState.depthFunc = depthFunc;
  681. }
  682. public setDepthFunctionToGreater(): void {
  683. this._depthCullingState.depthFunc = this._gl.GREATER;
  684. }
  685. public setDepthFunctionToGreaterOrEqual(): void {
  686. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  687. }
  688. public setDepthFunctionToLess(): void {
  689. this._depthCullingState.depthFunc = this._gl.LESS;
  690. }
  691. public setDepthFunctionToLessOrEqual(): void {
  692. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  693. }
  694. public getStencilBuffer(): boolean {
  695. return this._stencilState.stencilTest;
  696. }
  697. public setStencilBuffer(enable: boolean): void {
  698. this._stencilState.stencilTest = enable;
  699. }
  700. public getStencilMask(): number {
  701. return this._stencilState.stencilMask;
  702. }
  703. public setStencilMask(mask: number): void {
  704. this._stencilState.stencilMask = mask;
  705. }
  706. public getStencilFunction(): number {
  707. return this._stencilState.stencilFunc;
  708. }
  709. public getStencilFunctionReference(): number {
  710. return this._stencilState.stencilFuncRef;
  711. }
  712. public getStencilFunctionMask(): number {
  713. return this._stencilState.stencilFuncMask;
  714. }
  715. public setStencilFunction(stencilFunc: number) {
  716. this._stencilState.stencilFunc = stencilFunc;
  717. }
  718. public setStencilFunctionReference(reference: number) {
  719. this._stencilState.stencilFuncRef = reference;
  720. }
  721. public setStencilFunctionMask(mask: number) {
  722. this._stencilState.stencilFuncMask = mask;
  723. }
  724. public getStencilOperationFail(): number {
  725. return this._stencilState.stencilOpStencilFail;
  726. }
  727. public getStencilOperationDepthFail(): number {
  728. return this._stencilState.stencilOpDepthFail;
  729. }
  730. public getStencilOperationPass(): number {
  731. return this._stencilState.stencilOpStencilDepthPass;
  732. }
  733. public setStencilOperationFail(operation: number): void {
  734. this._stencilState.stencilOpStencilFail = operation;
  735. }
  736. public setStencilOperationDepthFail(operation: number): void {
  737. this._stencilState.stencilOpDepthFail = operation;
  738. }
  739. public setStencilOperationPass(operation: number): void {
  740. this._stencilState.stencilOpStencilDepthPass = operation;
  741. }
  742. /**
  743. * stop executing a render loop function and remove it from the execution array
  744. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  745. */
  746. public stopRenderLoop(renderFunction?: () => void): void {
  747. if (!renderFunction) {
  748. this._activeRenderLoops = [];
  749. return;
  750. }
  751. var index = this._activeRenderLoops.indexOf(renderFunction);
  752. if (index >= 0) {
  753. this._activeRenderLoops.splice(index, 1);
  754. }
  755. }
  756. public _renderLoop(): void {
  757. var shouldRender = true;
  758. if (!this.renderEvenInBackground && this._windowIsBackground) {
  759. shouldRender = false;
  760. }
  761. if (shouldRender) {
  762. // Start new frame
  763. this.beginFrame();
  764. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  765. var renderFunction = this._activeRenderLoops[index];
  766. renderFunction();
  767. }
  768. // Present
  769. this.endFrame();
  770. }
  771. if (this._activeRenderLoops.length > 0) {
  772. // Register new frame
  773. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  774. } else {
  775. this._renderingQueueLaunched = false;
  776. }
  777. }
  778. /**
  779. * Register and execute a render loop. The engine can have more than one render function.
  780. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  781. * @example
  782. * engine.runRenderLoop(function () {
  783. * scene.render()
  784. * })
  785. */
  786. public runRenderLoop(renderFunction: () => void): void {
  787. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  788. return;
  789. }
  790. this._activeRenderLoops.push(renderFunction);
  791. if (!this._renderingQueueLaunched) {
  792. this._renderingQueueLaunched = true;
  793. this._bindedRenderFunction = this._renderLoop.bind(this);
  794. Tools.QueueNewFrame(this._bindedRenderFunction);
  795. }
  796. }
  797. /**
  798. * Toggle full screen mode.
  799. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  800. * @param {any} options - an options object to be sent to the requestFullscreen function
  801. */
  802. public switchFullscreen(requestPointerLock: boolean): void {
  803. if (this.isFullscreen) {
  804. Tools.ExitFullscreen();
  805. } else {
  806. this._pointerLockRequested = requestPointerLock;
  807. Tools.RequestFullscreen(this._renderingCanvas);
  808. }
  809. }
  810. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  811. this.applyStates();
  812. var mode = 0;
  813. if (backBuffer && color) {
  814. this._gl.clearColor(color.r, color.g, color.b, color.a);
  815. mode |= this._gl.COLOR_BUFFER_BIT;
  816. }
  817. if (depth) {
  818. this._gl.clearDepth(1.0);
  819. mode |= this._gl.DEPTH_BUFFER_BIT;
  820. }
  821. if (stencil) {
  822. this._gl.clearStencil(0);
  823. mode |= this._gl.STENCIL_BUFFER_BIT;
  824. }
  825. this._gl.clear(mode);
  826. }
  827. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  828. let gl = this._gl;
  829. // Save state
  830. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  831. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  832. // Change state
  833. gl.enable(gl.SCISSOR_TEST);
  834. gl.scissor(x, y, width, height);
  835. // Clear
  836. this.clear(clearColor, true, true, true);
  837. // Restore state
  838. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  839. if (curScissor === true) {
  840. gl.enable(gl.SCISSOR_TEST);
  841. } else {
  842. gl.disable(gl.SCISSOR_TEST);
  843. }
  844. }
  845. /**
  846. * Set the WebGL's viewport
  847. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  848. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  849. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  850. */
  851. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  852. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  853. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  854. var x = viewport.x || 0;
  855. var y = viewport.y || 0;
  856. this._cachedViewport = viewport;
  857. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  858. }
  859. /**
  860. * Directly set the WebGL Viewport
  861. * The x, y, width & height are directly passed to the WebGL call
  862. * @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.
  863. */
  864. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  865. let currentViewport = this._cachedViewport;
  866. this._cachedViewport = null;
  867. this._gl.viewport(x, y, width, height);
  868. return currentViewport;
  869. }
  870. public beginFrame(): void {
  871. this._measureFps();
  872. }
  873. public endFrame(): void {
  874. //force a flush in case we are using a bad OS.
  875. if (this._badOS) {
  876. this.flushFramebuffer();
  877. }
  878. //submit frame to the vr device, if enabled
  879. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  880. this._vrDisplayEnabled.submitFrame()
  881. }
  882. }
  883. /**
  884. * resize the view according to the canvas' size.
  885. * @example
  886. * window.addEventListener("resize", function () {
  887. * engine.resize();
  888. * });
  889. */
  890. public resize(): void {
  891. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  892. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  893. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  894. }
  895. /**
  896. * force a specific size of the canvas
  897. * @param {number} width - the new canvas' width
  898. * @param {number} height - the new canvas' height
  899. */
  900. public setSize(width: number, height: number): void {
  901. this._renderingCanvas.width = width;
  902. this._renderingCanvas.height = height;
  903. for (var index = 0; index < this.scenes.length; index++) {
  904. var scene = this.scenes[index];
  905. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  906. var cam = scene.cameras[camIndex];
  907. cam._currentRenderId = 0;
  908. }
  909. }
  910. }
  911. //WebVR functions
  912. public initWebVR() {
  913. if (!this.vrDisplaysPromise) {
  914. this._getVRDisplays();
  915. }
  916. }
  917. public enableVR(vrDevice) {
  918. this._vrDisplayEnabled = vrDevice;
  919. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  920. }
  921. public disableVR() {
  922. if (this._vrDisplayEnabled) {
  923. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  924. }
  925. }
  926. private _onVRFullScreenTriggered = () => {
  927. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  928. //get the old size before we change
  929. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  930. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  931. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  932. //But actually, no browser follow the specs...
  933. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  934. //get the width and height, change the render size
  935. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  936. var width, height;
  937. this.setHardwareScalingLevel(1);
  938. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  939. } else {
  940. //When the specs are implemented, need to uncomment this.
  941. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  942. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  943. this.setSize(this._oldSize.width, this._oldSize.height);
  944. this._vrDisplayEnabled = undefined;
  945. }
  946. }
  947. private _getVRDisplays() {
  948. var getWebVRDevices = (devices: Array<any>) => {
  949. var size = devices.length;
  950. var i = 0;
  951. this._vrDisplays = devices.filter(function (device) {
  952. return devices[i] instanceof VRDisplay;
  953. });
  954. return this._vrDisplays;
  955. }
  956. //using a key due to typescript
  957. if (navigator.getVRDisplays) {
  958. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  959. }
  960. }
  961. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number): void {
  962. this._currentRenderTarget = texture;
  963. this.bindUnboundFramebuffer(texture._framebuffer);
  964. var gl = this._gl;
  965. if (texture.isCube) {
  966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  967. }
  968. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  969. this.wipeCaches();
  970. }
  971. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  972. if (this._currentFramebuffer !== framebuffer) {
  973. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  974. this._currentFramebuffer = framebuffer;
  975. }
  976. }
  977. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false): void {
  978. this._currentRenderTarget = null;
  979. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  980. var gl = this._gl;
  981. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  982. gl.generateMipmap(gl.TEXTURE_2D);
  983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  984. }
  985. this.bindUnboundFramebuffer(null);
  986. }
  987. public generateMipMapsForCubemap(texture: WebGLTexture) {
  988. if (texture.generateMipMaps) {
  989. var gl = this._gl;
  990. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  991. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  992. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  993. }
  994. }
  995. public flushFramebuffer(): void {
  996. this._gl.flush();
  997. }
  998. public restoreDefaultFramebuffer(): void {
  999. this._currentRenderTarget = null;
  1000. this.bindUnboundFramebuffer(null);
  1001. this.setViewport(this._cachedViewport);
  1002. this.wipeCaches();
  1003. }
  1004. // VBOs
  1005. private _resetVertexBufferBinding(): void {
  1006. this.bindArrayBuffer(null);
  1007. this._cachedVertexBuffers = null;
  1008. }
  1009. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1010. var vbo = this._gl.createBuffer();
  1011. this.bindArrayBuffer(vbo);
  1012. if (vertices instanceof Float32Array) {
  1013. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1014. } else {
  1015. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1016. }
  1017. this._resetVertexBufferBinding();
  1018. vbo.references = 1;
  1019. return vbo;
  1020. }
  1021. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1022. var vbo = this._gl.createBuffer();
  1023. this.bindArrayBuffer(vbo);
  1024. if (vertices instanceof Float32Array) {
  1025. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1026. } else {
  1027. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1028. }
  1029. this._resetVertexBufferBinding();
  1030. vbo.references = 1;
  1031. return vbo;
  1032. }
  1033. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1034. this.bindArrayBuffer(vertexBuffer);
  1035. if (offset === undefined) {
  1036. offset = 0;
  1037. }
  1038. if (count === undefined) {
  1039. if (vertices instanceof Float32Array) {
  1040. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1041. } else {
  1042. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1043. }
  1044. } else {
  1045. if (vertices instanceof Float32Array) {
  1046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1047. } else {
  1048. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1049. }
  1050. }
  1051. this._resetVertexBufferBinding();
  1052. }
  1053. private _resetIndexBufferBinding(): void {
  1054. this.bindIndexBuffer(null);
  1055. this._cachedIndexBuffer = null;
  1056. }
  1057. public createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer {
  1058. var vbo = this._gl.createBuffer();
  1059. this.bindIndexBuffer(vbo);
  1060. // Check for 32 bits indices
  1061. var arrayBuffer;
  1062. var need32Bits = false;
  1063. if (this._caps.uintIndices) {
  1064. for (var index = 0; index < indices.length; index++) {
  1065. if (indices[index] > 65535) {
  1066. need32Bits = true;
  1067. break;
  1068. }
  1069. }
  1070. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1071. } else {
  1072. arrayBuffer = new Uint16Array(indices);
  1073. }
  1074. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1075. this._resetIndexBufferBinding();
  1076. vbo.references = 1;
  1077. vbo.is32Bits = need32Bits;
  1078. return vbo;
  1079. }
  1080. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1081. if (!this._vaoRecordInProgress) {
  1082. this._unBindVertexArrayObject();
  1083. }
  1084. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1085. }
  1086. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1087. if (!this._vaoRecordInProgress) {
  1088. this._unBindVertexArrayObject();
  1089. }
  1090. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1091. }
  1092. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1093. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1094. this._gl.bindBuffer(target, buffer);
  1095. this._currentBoundBuffer[target] = buffer;
  1096. }
  1097. }
  1098. public updateArrayBuffer(data: Float32Array): void {
  1099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1100. }
  1101. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1102. var pointer = this._currentBufferPointers[indx];
  1103. var changed = false;
  1104. if (!pointer) {
  1105. changed = true;
  1106. this._currentBufferPointers[indx] = { indx, size, type, normalized, stride, offset, buffer: buffer };
  1107. } else {
  1108. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1109. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1110. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1111. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1112. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1113. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1114. }
  1115. if (changed || this._vaoRecordInProgress) {
  1116. this.bindArrayBuffer(buffer);
  1117. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1118. }
  1119. }
  1120. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1121. if (indexBuffer == null) {
  1122. return;
  1123. }
  1124. if (this._cachedIndexBuffer !== indexBuffer) {
  1125. this._cachedIndexBuffer = indexBuffer;
  1126. this.bindIndexBuffer(indexBuffer);
  1127. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1128. }
  1129. }
  1130. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1131. var attributes = effect.getAttributesNames();
  1132. if (!this._vaoRecordInProgress) {
  1133. this._unBindVertexArrayObject();
  1134. }
  1135. this.unbindAllAttributes();
  1136. for (var index = 0; index < attributes.length; index++) {
  1137. var order = effect.getAttributeLocation(index);
  1138. if (order >= 0) {
  1139. var vertexBuffer = vertexBuffers[attributes[index]];
  1140. if (!vertexBuffer) {
  1141. continue;
  1142. }
  1143. this._gl.enableVertexAttribArray(order);
  1144. if (!this._vaoRecordInProgress) {
  1145. this._vertexAttribArraysEnabled[order] = true;
  1146. }
  1147. var buffer = vertexBuffer.getBuffer();
  1148. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1149. if (vertexBuffer.getIsInstanced()) {
  1150. this._gl.vertexAttribDivisor(order, 1);
  1151. if (!this._vaoRecordInProgress) {
  1152. this._currentInstanceLocations.push(order);
  1153. this._currentInstanceBuffers.push(buffer);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. }
  1159. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1160. var vao = this._gl.createVertexArray();
  1161. this._vaoRecordInProgress = true;
  1162. this._gl.bindVertexArray(vao);
  1163. this._mustWipeVertexAttributes = true;
  1164. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1165. this.bindIndexBuffer(indexBuffer);
  1166. this._vaoRecordInProgress = false;
  1167. this._gl.bindVertexArray(null);
  1168. return vao;
  1169. }
  1170. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1171. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1172. this._cachedVertexArrayObject = vertexArrayObject;
  1173. this._gl.bindVertexArray(vertexArrayObject);
  1174. this._cachedVertexBuffers = null;
  1175. this._cachedIndexBuffer = null;
  1176. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1177. this._mustWipeVertexAttributes = true;
  1178. }
  1179. }
  1180. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1181. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1182. this._cachedVertexBuffers = vertexBuffer;
  1183. this._cachedEffectForVertexBuffers = effect;
  1184. let attributesCount = effect.getAttributesCount();
  1185. this._unBindVertexArrayObject();
  1186. this.unbindAllAttributes();
  1187. var offset = 0;
  1188. for (var index = 0; index < attributesCount; index++) {
  1189. if (index < vertexDeclaration.length) {
  1190. var order = effect.getAttributeLocation(index);
  1191. if (order >= 0) {
  1192. this._gl.enableVertexAttribArray(order);
  1193. this._vertexAttribArraysEnabled[order] = true;
  1194. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1195. }
  1196. offset += vertexDeclaration[index] * 4;
  1197. }
  1198. }
  1199. }
  1200. this._bindIndexBufferWithCache(indexBuffer);
  1201. }
  1202. private _unBindVertexArrayObject(): void {
  1203. if (!this._cachedVertexArrayObject) {
  1204. return;
  1205. }
  1206. this._cachedVertexArrayObject = null;
  1207. this._gl.bindVertexArray(null);
  1208. }
  1209. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1210. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1211. this._cachedVertexBuffers = vertexBuffers;
  1212. this._cachedEffectForVertexBuffers = effect;
  1213. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1214. }
  1215. this._bindIndexBufferWithCache(indexBuffer);
  1216. }
  1217. public unbindInstanceAttributes() {
  1218. var boundBuffer;
  1219. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1220. var instancesBuffer = this._currentInstanceBuffers[i];
  1221. if (boundBuffer != instancesBuffer) {
  1222. boundBuffer = instancesBuffer;
  1223. this.bindArrayBuffer(instancesBuffer);
  1224. }
  1225. var offsetLocation = this._currentInstanceLocations[i];
  1226. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1227. }
  1228. this._currentInstanceBuffers.length = 0;
  1229. this._currentInstanceLocations.length = 0;
  1230. }
  1231. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1232. this._gl.deleteVertexArray(vao);
  1233. }
  1234. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1235. buffer.references--;
  1236. if (buffer.references === 0) {
  1237. this._gl.deleteBuffer(buffer);
  1238. return true;
  1239. }
  1240. return false;
  1241. }
  1242. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1243. var buffer = this._gl.createBuffer();
  1244. buffer.capacity = capacity;
  1245. this.bindArrayBuffer(buffer);
  1246. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1247. return buffer;
  1248. }
  1249. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1250. this._gl.deleteBuffer(buffer);
  1251. }
  1252. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1253. this.bindArrayBuffer(instancesBuffer);
  1254. if (data) {
  1255. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1256. }
  1257. if ((<any>offsetLocations[0]).index !== undefined) {
  1258. let stride = 0;
  1259. for (let i = 0; i < offsetLocations.length; i++) {
  1260. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1261. stride += ai.attributeSize * 4;
  1262. }
  1263. for (let i = 0; i < offsetLocations.length; i++) {
  1264. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1265. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1266. this._gl.enableVertexAttribArray(ai.index);
  1267. this._vertexAttribArraysEnabled[ai.index] = true;
  1268. }
  1269. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1270. this._gl.vertexAttribDivisor(ai.index, 1);
  1271. this._currentInstanceLocations.push(ai.index);
  1272. this._currentInstanceBuffers.push(instancesBuffer);
  1273. }
  1274. } else {
  1275. for (let index = 0; index < 4; index++) {
  1276. let offsetLocation = <number>offsetLocations[index];
  1277. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1278. this._gl.enableVertexAttribArray(offsetLocation);
  1279. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1280. }
  1281. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1282. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1283. this._currentInstanceLocations.push(offsetLocation);
  1284. this._currentInstanceBuffers.push(instancesBuffer);
  1285. }
  1286. }
  1287. }
  1288. public applyStates() {
  1289. this._depthCullingState.apply(this._gl);
  1290. this._stencilState.apply(this._gl);
  1291. this._alphaState.apply(this._gl);
  1292. }
  1293. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1294. // Apply states
  1295. this.applyStates();
  1296. this._drawCalls.addCount(1, false);
  1297. // Render
  1298. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1299. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1300. if (instancesCount) {
  1301. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1302. return;
  1303. }
  1304. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1305. }
  1306. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1307. // Apply states
  1308. this.applyStates();
  1309. this._drawCalls.addCount(1, false);
  1310. if (instancesCount) {
  1311. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1312. return;
  1313. }
  1314. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1315. }
  1316. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1317. // Apply states
  1318. this.applyStates();
  1319. this._drawCalls.addCount(1, false);
  1320. if (instancesCount) {
  1321. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1322. return;
  1323. }
  1324. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1325. }
  1326. // Shaders
  1327. public _releaseEffect(effect: Effect): void {
  1328. if (this._compiledEffects[effect._key]) {
  1329. delete this._compiledEffects[effect._key];
  1330. if (effect.getProgram()) {
  1331. this._gl.deleteProgram(effect.getProgram());
  1332. }
  1333. }
  1334. }
  1335. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  1336. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1337. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1338. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1339. var name = vertex + "+" + fragment + "@" + defines;
  1340. if (this._compiledEffects[name]) {
  1341. return this._compiledEffects[name];
  1342. }
  1343. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1344. effect._key = name;
  1345. this._compiledEffects[name] = effect;
  1346. return effect;
  1347. }
  1348. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1349. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1350. return this.createEffect(
  1351. {
  1352. vertex: "particles",
  1353. fragmentElement: fragmentName
  1354. },
  1355. ["position", "color", "options"],
  1356. ["view", "projection"].concat(uniformsNames),
  1357. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1358. }
  1359. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1360. context = context || this._gl;
  1361. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1362. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1363. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1364. var shaderProgram = context.createProgram();
  1365. context.attachShader(shaderProgram, vertexShader);
  1366. context.attachShader(shaderProgram, fragmentShader);
  1367. context.linkProgram(shaderProgram);
  1368. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1369. if (!linked) {
  1370. var error = context.getProgramInfoLog(shaderProgram);
  1371. if (error) {
  1372. throw new Error(error);
  1373. }
  1374. }
  1375. context.deleteShader(vertexShader);
  1376. context.deleteShader(fragmentShader);
  1377. return shaderProgram;
  1378. }
  1379. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1380. var results = [];
  1381. for (var index = 0; index < uniformsNames.length; index++) {
  1382. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1383. }
  1384. return results;
  1385. }
  1386. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1387. var results = [];
  1388. for (var index = 0; index < attributesNames.length; index++) {
  1389. try {
  1390. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1391. } catch (e) {
  1392. results.push(-1);
  1393. }
  1394. }
  1395. return results;
  1396. }
  1397. public enableEffect(effect: Effect): void {
  1398. // Use program
  1399. this.setProgram(effect.getProgram());
  1400. this._currentEffect = effect;
  1401. if (effect.onBind) {
  1402. effect.onBind(effect);
  1403. }
  1404. }
  1405. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1406. if (!uniform)
  1407. return;
  1408. this._gl.uniform1iv(uniform, array);
  1409. }
  1410. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1411. if (!uniform || array.length % 2 !== 0)
  1412. return;
  1413. this._gl.uniform2iv(uniform, array);
  1414. }
  1415. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1416. if (!uniform || array.length % 3 !== 0)
  1417. return;
  1418. this._gl.uniform3iv(uniform, array);
  1419. }
  1420. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1421. if (!uniform || array.length % 4 !== 0)
  1422. return;
  1423. this._gl.uniform4iv(uniform, array);
  1424. }
  1425. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1426. if (!uniform)
  1427. return;
  1428. this._gl.uniform1fv(uniform, array);
  1429. }
  1430. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1431. if (!uniform || array.length % 2 !== 0)
  1432. return;
  1433. this._gl.uniform2fv(uniform, array);
  1434. }
  1435. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1436. if (!uniform || array.length % 3 !== 0)
  1437. return;
  1438. this._gl.uniform3fv(uniform, array);
  1439. }
  1440. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1441. if (!uniform || array.length % 4 !== 0)
  1442. return;
  1443. this._gl.uniform4fv(uniform, array);
  1444. }
  1445. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1446. if (!uniform)
  1447. return;
  1448. this._gl.uniform1fv(uniform, <any>array);
  1449. }
  1450. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1451. if (!uniform || array.length % 2 !== 0)
  1452. return;
  1453. this._gl.uniform2fv(uniform, <any>array);
  1454. }
  1455. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1456. if (!uniform || array.length % 3 !== 0)
  1457. return;
  1458. this._gl.uniform3fv(uniform, <any>array);
  1459. }
  1460. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1461. if (!uniform || array.length % 4 !== 0)
  1462. return;
  1463. this._gl.uniform4fv(uniform, <any>array);
  1464. }
  1465. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1466. if (!uniform)
  1467. return;
  1468. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1469. }
  1470. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1471. if (!uniform)
  1472. return;
  1473. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1474. }
  1475. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1476. if (!uniform)
  1477. return;
  1478. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1479. }
  1480. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1481. if (!uniform)
  1482. return;
  1483. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1484. }
  1485. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1486. if (!uniform)
  1487. return;
  1488. this._gl.uniform1f(uniform, value);
  1489. }
  1490. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1491. if (!uniform)
  1492. return;
  1493. this._gl.uniform2f(uniform, x, y);
  1494. }
  1495. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1496. if (!uniform)
  1497. return;
  1498. this._gl.uniform3f(uniform, x, y, z);
  1499. }
  1500. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1501. if (!uniform)
  1502. return;
  1503. this._gl.uniform1i(uniform, bool);
  1504. }
  1505. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1506. if (!uniform)
  1507. return;
  1508. this._gl.uniform4f(uniform, x, y, z, w);
  1509. }
  1510. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1511. if (!uniform)
  1512. return;
  1513. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1514. }
  1515. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1516. if (!uniform)
  1517. return;
  1518. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1519. }
  1520. // States
  1521. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1522. // Culling
  1523. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1524. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1525. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1526. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1527. if (culling) {
  1528. this._depthCullingState.cullFace = cullFace;
  1529. this._depthCullingState.cull = true;
  1530. } else {
  1531. this._depthCullingState.cull = false;
  1532. }
  1533. }
  1534. // Z offset
  1535. this._depthCullingState.zOffset = zOffset;
  1536. }
  1537. public setDepthBuffer(enable: boolean): void {
  1538. this._depthCullingState.depthTest = enable;
  1539. }
  1540. public getDepthWrite(): boolean {
  1541. return this._depthCullingState.depthMask;
  1542. }
  1543. public setDepthWrite(enable: boolean): void {
  1544. this._depthCullingState.depthMask = enable;
  1545. }
  1546. public setColorWrite(enable: boolean): void {
  1547. this._gl.colorMask(enable, enable, enable, enable);
  1548. }
  1549. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1550. if (this._alphaMode === mode) {
  1551. return;
  1552. }
  1553. switch (mode) {
  1554. case Engine.ALPHA_DISABLE:
  1555. this._alphaState.alphaBlend = false;
  1556. break;
  1557. case Engine.ALPHA_PREMULTIPLIED:
  1558. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1559. this._alphaState.alphaBlend = true;
  1560. break;
  1561. case Engine.ALPHA_COMBINE:
  1562. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1563. this._alphaState.alphaBlend = true;
  1564. break;
  1565. case Engine.ALPHA_ONEONE:
  1566. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1567. this._alphaState.alphaBlend = true;
  1568. break;
  1569. case Engine.ALPHA_ADD:
  1570. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1571. this._alphaState.alphaBlend = true;
  1572. break;
  1573. case Engine.ALPHA_SUBTRACT:
  1574. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1575. this._alphaState.alphaBlend = true;
  1576. break;
  1577. case Engine.ALPHA_MULTIPLY:
  1578. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1579. this._alphaState.alphaBlend = true;
  1580. break;
  1581. case Engine.ALPHA_MAXIMIZED:
  1582. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1583. this._alphaState.alphaBlend = true;
  1584. break;
  1585. }
  1586. if (!noDepthWriteChange) {
  1587. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1588. }
  1589. this._alphaMode = mode;
  1590. }
  1591. public getAlphaMode(): number {
  1592. return this._alphaMode;
  1593. }
  1594. public setAlphaTesting(enable: boolean): void {
  1595. this._alphaTest = enable;
  1596. }
  1597. public getAlphaTesting(): boolean {
  1598. return this._alphaTest;
  1599. }
  1600. // Textures
  1601. public wipeCaches(): void {
  1602. this.resetTextureCache();
  1603. this._currentEffect = null;
  1604. this._stencilState.reset();
  1605. this._depthCullingState.reset();
  1606. this.setDepthFunctionToLessOrEqual();
  1607. this._alphaState.reset();
  1608. this._cachedVertexBuffers = null;
  1609. this._cachedIndexBuffer = null;
  1610. this._cachedEffectForVertexBuffers = null;
  1611. this._unBindVertexArrayObject();
  1612. this.bindIndexBuffer(null);
  1613. this.bindArrayBuffer(null);
  1614. }
  1615. /**
  1616. * Set the compressed texture format to use, based on the formats you have, and the formats
  1617. * supported by the hardware / browser.
  1618. *
  1619. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  1620. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  1621. * to API arguments needed to compressed textures. This puts the burden on the container
  1622. * generator to house the arcane code for determining these for current & future formats.
  1623. *
  1624. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  1625. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  1626. *
  1627. * Note: The result of this call is not taken into account when a texture is base64.
  1628. *
  1629. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  1630. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  1631. *
  1632. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  1633. * @returns The extension selected.
  1634. */
  1635. public setTextureFormatToUse(formatsAvailable : Array<string>) : string {
  1636. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  1637. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  1638. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  1639. return this._textureFormatInUse = this._texturesSupported[i];
  1640. }
  1641. }
  1642. }
  1643. // actively set format to nothing, to allow this to be called more than once
  1644. // and possibly fail the 2nd time
  1645. return this._textureFormatInUse = null;
  1646. }
  1647. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: any = null, fallBack?: WebGLTexture): WebGLTexture {
  1648. var texture = fallBack ? fallBack : this._gl.createTexture();
  1649. var extension: string;
  1650. var isKTX = false;
  1651. var fromData: any = false;
  1652. var url = String(urlArg);
  1653. if (url.substr(0, 5) === "data:") {
  1654. fromData = true;
  1655. }
  1656. if (!fromData) {
  1657. var lastDot = url.lastIndexOf('.')
  1658. extension = url.substring(lastDot).toLowerCase();
  1659. if (this._textureFormatInUse && !fromData && !fallBack) {
  1660. extension = this._textureFormatInUse;
  1661. url = url.substring(0, lastDot) + this._textureFormatInUse;
  1662. isKTX = true;
  1663. }
  1664. } else {
  1665. var oldUrl = url;
  1666. fromData = oldUrl.split(':');
  1667. url = oldUrl;
  1668. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1669. }
  1670. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1671. var isTGA = (extension === ".tga");
  1672. scene._addPendingData(texture);
  1673. texture.url = url;
  1674. texture.noMipmap = noMipmap;
  1675. texture.references = 1;
  1676. texture.samplingMode = samplingMode;
  1677. texture.onLoadedCallbacks = [];
  1678. if (onLoad) {
  1679. texture.onLoadedCallbacks.push(onLoad);
  1680. }
  1681. if (!fallBack) this._loadedTexturesCache.push(texture);
  1682. var onerror = () => {
  1683. scene._removePendingData(texture);
  1684. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  1685. if (isKTX) {
  1686. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  1687. } else if (onError) {
  1688. onError();
  1689. }
  1690. };
  1691. var callback: (arrayBuffer: any) => void;
  1692. if (isKTX || isTGA || isDDS){
  1693. if (isKTX) {
  1694. callback = (data) => {
  1695. var ktx = new Internals.KhronosTextureContainer(data, 1);
  1696. prepareWebGLTexture(texture, this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  1697. ktx.uploadLevels(this._gl, !noMipmap);
  1698. }, samplingMode);
  1699. };
  1700. } else if (isTGA) {
  1701. callback = (arrayBuffer) => {
  1702. var data = new Uint8Array(arrayBuffer);
  1703. var header = Internals.TGATools.GetTGAHeader(data);
  1704. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1705. Internals.TGATools.UploadContent(this._gl, data);
  1706. }, samplingMode);
  1707. };
  1708. } else if (isDDS) {
  1709. callback = (data) => {
  1710. var info = Internals.DDSTools.GetDDSInfo(data);
  1711. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1712. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1713. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1714. }, samplingMode);
  1715. };
  1716. }
  1717. if (!(fromData instanceof Array))
  1718. Tools.LoadFile(url, data => {
  1719. callback(data);
  1720. }, null, scene.database, true, onerror);
  1721. else
  1722. callback(buffer);
  1723. } else {
  1724. var onload = (img) => {
  1725. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1726. var isPot = (img.width === potWidth && img.height === potHeight);
  1727. if (!isPot) {
  1728. this._prepareWorkingCanvas();
  1729. this._workingCanvas.width = potWidth;
  1730. this._workingCanvas.height = potHeight;
  1731. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1732. this._workingContext.imageSmoothingEnabled = false;
  1733. this._workingContext.mozImageSmoothingEnabled = false;
  1734. this._workingContext.oImageSmoothingEnabled = false;
  1735. this._workingContext.webkitImageSmoothingEnabled = false;
  1736. this._workingContext.msImageSmoothingEnabled = false;
  1737. }
  1738. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1739. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1740. this._workingContext.imageSmoothingEnabled = true;
  1741. this._workingContext.mozImageSmoothingEnabled = true;
  1742. this._workingContext.oImageSmoothingEnabled = true;
  1743. this._workingContext.webkitImageSmoothingEnabled = true;
  1744. this._workingContext.msImageSmoothingEnabled = true;
  1745. }
  1746. }
  1747. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1748. }, samplingMode);
  1749. };
  1750. if (!(fromData instanceof Array))
  1751. Tools.LoadImage(url, onload, onerror, scene.database);
  1752. else
  1753. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1754. }
  1755. return texture;
  1756. }
  1757. private _getInternalFormat(format: number): number {
  1758. var internalFormat = this._gl.RGBA;
  1759. switch (format) {
  1760. case Engine.TEXTUREFORMAT_ALPHA:
  1761. internalFormat = this._gl.ALPHA;
  1762. break;
  1763. case Engine.TEXTUREFORMAT_LUMINANCE:
  1764. internalFormat = this._gl.LUMINANCE;
  1765. break;
  1766. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1767. internalFormat = this._gl.LUMINANCE_ALPHA;
  1768. break;
  1769. case Engine.TEXTUREFORMAT_RGB:
  1770. internalFormat = this._gl.RGB;
  1771. break;
  1772. case Engine.TEXTUREFORMAT_RGBA:
  1773. internalFormat = this._gl.RGBA;
  1774. break;
  1775. }
  1776. return internalFormat;
  1777. }
  1778. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  1779. var internalFormat = this._getInternalFormat(format);
  1780. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1781. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1782. if (texture._width % 4 !== 0) {
  1783. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1784. }
  1785. if (compression) {
  1786. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1787. } else {
  1788. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1789. }
  1790. if (texture.generateMipMaps) {
  1791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1792. }
  1793. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1794. this.resetTextureCache();
  1795. texture.isReady = true;
  1796. }
  1797. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  1798. var texture = this._gl.createTexture();
  1799. texture._baseWidth = width;
  1800. texture._baseHeight = height;
  1801. texture._width = width;
  1802. texture._height = height;
  1803. texture.references = 1;
  1804. this.updateRawTexture(texture, data, format, invertY, compression);
  1805. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1806. // Filters
  1807. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1808. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1809. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1810. if (generateMipMaps) {
  1811. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1812. }
  1813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1814. texture.samplingMode = samplingMode;
  1815. this._loadedTexturesCache.push(texture);
  1816. return texture;
  1817. }
  1818. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1819. var texture = this._gl.createTexture();
  1820. texture._baseWidth = width;
  1821. texture._baseHeight = height;
  1822. if (generateMipMaps) {
  1823. width = Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1824. height = Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1825. }
  1826. this.resetTextureCache();
  1827. texture._width = width;
  1828. texture._height = height;
  1829. texture.isReady = false;
  1830. texture.generateMipMaps = generateMipMaps;
  1831. texture.references = 1;
  1832. texture.samplingMode = samplingMode;
  1833. this.updateTextureSamplingMode(samplingMode, texture);
  1834. this._loadedTexturesCache.push(texture);
  1835. return texture;
  1836. }
  1837. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  1838. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1839. if (texture.isCube) {
  1840. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1841. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1842. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1843. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1844. } else {
  1845. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1846. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1849. }
  1850. texture.samplingMode = samplingMode;
  1851. }
  1852. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false): void {
  1853. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1854. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1855. if (premulAlpha) {
  1856. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1857. }
  1858. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1859. if (texture.generateMipMaps) {
  1860. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1861. }
  1862. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1863. if (premulAlpha) {
  1864. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  1865. }
  1866. this.resetTextureCache();
  1867. texture.isReady = true;
  1868. }
  1869. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1870. if (texture._isDisabled) {
  1871. return;
  1872. }
  1873. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1874. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1875. try {
  1876. // Testing video texture support
  1877. if (this._videoTextureSupported === undefined) {
  1878. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1879. if (this._gl.getError() !== 0) {
  1880. this._videoTextureSupported = false;
  1881. } else {
  1882. this._videoTextureSupported = true;
  1883. }
  1884. }
  1885. // Copy video through the current working canvas if video texture is not supported
  1886. if (!this._videoTextureSupported) {
  1887. if (!texture._workingCanvas) {
  1888. texture._workingCanvas = document.createElement("canvas");
  1889. texture._workingContext = texture._workingCanvas.getContext("2d");
  1890. texture._workingCanvas.width = texture._width;
  1891. texture._workingCanvas.height = texture._height;
  1892. }
  1893. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1894. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1895. } else {
  1896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1897. }
  1898. if (texture.generateMipMaps) {
  1899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1900. }
  1901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1902. this.resetTextureCache();
  1903. texture.isReady = true;
  1904. } catch (ex) {
  1905. // Something unexpected
  1906. // Let's disable the texture
  1907. texture._isDisabled = true;
  1908. }
  1909. }
  1910. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1911. // old version had a "generateMipMaps" arg instead of options.
  1912. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1913. // in the same way, generateDepthBuffer is defaulted to true
  1914. var generateMipMaps = false;
  1915. var generateDepthBuffer = true;
  1916. var generateStencilBuffer = false;
  1917. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1918. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1919. if (options !== undefined) {
  1920. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1921. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1922. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1923. type = options.type === undefined ? type : options.type;
  1924. if (options.samplingMode !== undefined) {
  1925. samplingMode = options.samplingMode;
  1926. }
  1927. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1928. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1929. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1930. }
  1931. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  1932. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  1933. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1934. }
  1935. }
  1936. var gl = this._gl;
  1937. var texture = gl.createTexture();
  1938. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1939. var width = size.width || size;
  1940. var height = size.height || size;
  1941. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1942. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1943. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1944. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1945. }
  1946. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1947. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1950. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  1951. var depthStencilBuffer: WebGLRenderbuffer;
  1952. // Create the depth/stencil buffer
  1953. if (generateStencilBuffer) {
  1954. depthStencilBuffer = gl.createRenderbuffer();
  1955. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1956. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  1957. }
  1958. else if (generateDepthBuffer) {
  1959. depthStencilBuffer = gl.createRenderbuffer();
  1960. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1961. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1962. }
  1963. // Create the framebuffer
  1964. var framebuffer = gl.createFramebuffer();
  1965. this.bindUnboundFramebuffer(framebuffer);
  1966. // Manage attachments
  1967. if (generateStencilBuffer) {
  1968. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1969. }
  1970. else if (generateDepthBuffer) {
  1971. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1972. }
  1973. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1974. if (generateMipMaps) {
  1975. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1976. }
  1977. // Unbind
  1978. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1979. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1980. this.bindUnboundFramebuffer(null);
  1981. texture._framebuffer = framebuffer;
  1982. if (generateDepthBuffer) {
  1983. texture._depthBuffer = depthStencilBuffer;
  1984. }
  1985. texture._baseWidth = width;
  1986. texture._baseHeight = height;
  1987. texture._width = width;
  1988. texture._height = height;
  1989. texture.isReady = true;
  1990. texture.generateMipMaps = generateMipMaps;
  1991. texture.references = 1;
  1992. texture.samplingMode = samplingMode;
  1993. texture.type = type;
  1994. this.resetTextureCache();
  1995. this._loadedTexturesCache.push(texture);
  1996. return texture;
  1997. }
  1998. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  1999. var gl = this._gl;
  2000. var texture = gl.createTexture();
  2001. var generateMipMaps = true;
  2002. var generateDepthBuffer = true;
  2003. var generateStencilBuffer = false;
  2004. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2005. if (options !== undefined) {
  2006. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2007. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2008. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2009. if (options.samplingMode !== undefined) {
  2010. samplingMode = options.samplingMode;
  2011. }
  2012. }
  2013. texture.isCube = true;
  2014. texture.references = 1;
  2015. texture.generateMipMaps = generateMipMaps;
  2016. texture.references = 1;
  2017. texture.samplingMode = samplingMode;
  2018. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2019. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2020. for (var face = 0; face < 6; face++) {
  2021. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2022. }
  2023. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2027. // Create the depth buffer
  2028. var depthStencilBuffer: WebGLRenderbuffer;
  2029. // Create the depth/stencil buffer
  2030. if (generateStencilBuffer) {
  2031. depthStencilBuffer = gl.createRenderbuffer();
  2032. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2033. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  2034. }
  2035. else if (generateDepthBuffer) {
  2036. depthStencilBuffer = gl.createRenderbuffer();
  2037. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2038. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  2039. }
  2040. // Create the framebuffer
  2041. var framebuffer = gl.createFramebuffer();
  2042. this.bindUnboundFramebuffer(framebuffer);
  2043. // Manage attachments
  2044. if (generateStencilBuffer) {
  2045. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2046. }
  2047. else if (generateDepthBuffer) {
  2048. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2049. }
  2050. // Mipmaps
  2051. if (texture.generateMipMaps) {
  2052. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2053. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2054. }
  2055. // Unbind
  2056. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2057. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2058. this.bindUnboundFramebuffer(null);
  2059. texture._framebuffer = framebuffer;
  2060. if (generateDepthBuffer) {
  2061. texture._depthBuffer = depthStencilBuffer;
  2062. }
  2063. texture._width = size;
  2064. texture._height = size;
  2065. texture.isReady = true;
  2066. this.resetTextureCache();
  2067. this._loadedTexturesCache.push(texture);
  2068. return texture;
  2069. }
  2070. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: () => void = null, onError: () => void = null): WebGLTexture {
  2071. var gl = this._gl;
  2072. var texture = gl.createTexture();
  2073. texture.isCube = true;
  2074. texture.url = rootUrl;
  2075. texture.references = 1;
  2076. texture.onLoadedCallbacks = [];
  2077. var isKTX = false;
  2078. var lastDot = rootUrl.lastIndexOf('.');
  2079. var extension = rootUrl.substring(lastDot).toLowerCase();
  2080. if (this._textureFormatInUse) {
  2081. extension = this._textureFormatInUse;
  2082. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2083. isKTX = true;
  2084. }
  2085. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2086. if (isKTX) {
  2087. Tools.LoadFile(rootUrl, data => {
  2088. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2089. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2092. ktx.uploadLevels(this._gl, !noMipmap);
  2093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2097. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2098. this.resetTextureCache();
  2099. texture._width = ktx.pixelWidth;
  2100. texture._height = ktx.pixelHeight;
  2101. texture.isReady = true;
  2102. }, null, null, true, onError);
  2103. } else if (isDDS) {
  2104. Tools.LoadFile(rootUrl, data => {
  2105. var info = Internals.DDSTools.GetDDSInfo(data);
  2106. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2107. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2109. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  2110. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2111. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2112. }
  2113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2117. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2118. this.resetTextureCache();
  2119. texture._width = info.width;
  2120. texture._height = info.height;
  2121. texture.isReady = true;
  2122. }, null, null, true, onError);
  2123. } else {
  2124. cascadeLoad(rootUrl, scene, imgs => {
  2125. var width = Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  2126. var height = width;
  2127. this._prepareWorkingCanvas();
  2128. this._workingCanvas.width = width;
  2129. this._workingCanvas.height = height;
  2130. var faces = [
  2131. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2132. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2133. ];
  2134. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2135. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2136. for (var index = 0; index < faces.length; index++) {
  2137. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2138. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  2139. }
  2140. if (!noMipmap) {
  2141. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2142. }
  2143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2144. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2147. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2148. this.resetTextureCache();
  2149. texture._width = width;
  2150. texture._height = height;
  2151. texture.isReady = true;
  2152. texture.onLoadedCallbacks.forEach(callback => {
  2153. callback();
  2154. });
  2155. if (onLoad) {
  2156. onLoad();
  2157. }
  2158. }, files, onError);
  2159. }
  2160. this._loadedTexturesCache.push(texture);
  2161. return texture;
  2162. }
  2163. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  2164. texture._width = width;
  2165. texture._height = height;
  2166. texture._size = width * height;
  2167. texture._baseWidth = width;
  2168. texture._baseHeight = height;
  2169. }
  2170. public createRawCubeTexture(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  2171. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  2172. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][])): WebGLTexture {
  2173. var gl = this._gl;
  2174. var texture = gl.createTexture();
  2175. scene._addPendingData(texture);
  2176. texture.isCube = true;
  2177. texture.references = 1;
  2178. texture.url = url;
  2179. var textureType = gl.UNSIGNED_BYTE;
  2180. if (type === Engine.TEXTURETYPE_FLOAT) {
  2181. textureType = gl.FLOAT;
  2182. }
  2183. var internalFormat = this._getInternalFormat(format);
  2184. var needConversion = false;
  2185. if (internalFormat === gl.RGB) {
  2186. internalFormat = gl.RGBA;
  2187. needConversion = true;
  2188. }
  2189. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2190. var width = size;
  2191. var height = width;
  2192. var isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2193. texture._width = width;
  2194. texture._height = height;
  2195. var onerror = () => {
  2196. scene._removePendingData(texture);
  2197. };
  2198. var internalCallback = (data) => {
  2199. var rgbeDataArrays = callback(data);
  2200. var facesIndex = [
  2201. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2202. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2203. ];
  2204. width = texture._width;
  2205. height = texture._height;
  2206. isPot = (Tools.IsExponentOfTwo(width) && Tools.IsExponentOfTwo(height));
  2207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2208. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2209. if (mipmmapGenerator) {
  2210. var arrayTemp: ArrayBufferView[] = [];
  2211. // Data are known to be in +X +Y +Z -X -Y -Z
  2212. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  2213. arrayTemp.push(rgbeDataArrays[0]); // +X
  2214. arrayTemp.push(rgbeDataArrays[3]); // -X
  2215. arrayTemp.push(rgbeDataArrays[1]); // +Y
  2216. arrayTemp.push(rgbeDataArrays[4]); // -Y
  2217. arrayTemp.push(rgbeDataArrays[2]); // +Z
  2218. arrayTemp.push(rgbeDataArrays[5]); // -Z
  2219. var mipData = mipmmapGenerator(arrayTemp);
  2220. // mipData is order in +X -X +Y -Y +Z -Z
  2221. var mipFaces = [0, 2, 4, 1, 3, 5];
  2222. for (var level = 0; level < mipData.length; level++) {
  2223. var mipSize = width >> level;
  2224. for (let mipIndex in mipFaces) {
  2225. let mipFaceData = mipData[level][mipFaces[mipIndex]];
  2226. if (needConversion) {
  2227. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  2228. }
  2229. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  2230. }
  2231. }
  2232. }
  2233. else {
  2234. // Data are known to be in +X +Y +Z -X -Y -Z
  2235. for (let index = 0; index < facesIndex.length; index++) {
  2236. let faceData = rgbeDataArrays[index];
  2237. if (needConversion) {
  2238. faceData = this._convertRGBtoRGBATextureData(faceData, width, height, type);
  2239. }
  2240. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  2241. }
  2242. if (!noMipmap && isPot) {
  2243. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2244. }
  2245. else {
  2246. noMipmap = true;
  2247. }
  2248. }
  2249. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  2250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2252. }
  2253. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  2254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2256. }
  2257. else {
  2258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2260. }
  2261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2263. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2264. texture.isReady = true;
  2265. this.resetTextureCache();
  2266. scene._removePendingData(texture);
  2267. };
  2268. Tools.LoadFile(url, data => {
  2269. internalCallback(data);
  2270. }, onerror, scene.database, true);
  2271. return texture;
  2272. };
  2273. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  2274. // Create new RGBA data container.
  2275. var rgbaData: ArrayBufferView;
  2276. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  2277. rgbaData = new Float32Array(width * height * 4);
  2278. }
  2279. else {
  2280. rgbaData = new Uint32Array(width * height * 4);
  2281. }
  2282. // Convert each pixel.
  2283. for (let x = 0; x < width; x++) {
  2284. for (let y = 0; y < height; y++) {
  2285. let index = (y * width + x) * 3;
  2286. let newIndex = (y * width + x) * 4;
  2287. // Map Old Value to new value.
  2288. rgbaData[newIndex + 0] = rgbData[index + 0];
  2289. rgbaData[newIndex + 1] = rgbData[index + 1];
  2290. rgbaData[newIndex + 2] = rgbData[index + 2];
  2291. // Add fully opaque alpha channel.
  2292. rgbaData[newIndex + 3] = 1;
  2293. }
  2294. }
  2295. return rgbaData;
  2296. }
  2297. public _releaseTexture(texture: WebGLTexture): void {
  2298. var gl = this._gl;
  2299. if (texture._framebuffer) {
  2300. gl.deleteFramebuffer(texture._framebuffer);
  2301. }
  2302. if (texture._depthBuffer) {
  2303. gl.deleteRenderbuffer(texture._depthBuffer);
  2304. }
  2305. gl.deleteTexture(texture);
  2306. // Unbind channels
  2307. this.unbindAllTextures();
  2308. var index = this._loadedTexturesCache.indexOf(texture);
  2309. if (index !== -1) {
  2310. this._loadedTexturesCache.splice(index, 1);
  2311. }
  2312. }
  2313. private setProgram(program: WebGLProgram): void {
  2314. if (this._currentProgram !== program) {
  2315. this._gl.useProgram(program);
  2316. this._currentProgram = program;
  2317. }
  2318. }
  2319. public bindSamplers(effect: Effect): void {
  2320. this.setProgram(effect.getProgram());
  2321. var samplers = effect.getSamplers();
  2322. for (var index = 0; index < samplers.length; index++) {
  2323. var uniform = effect.getUniform(samplers[index]);
  2324. this._gl.uniform1i(uniform, index);
  2325. }
  2326. this._currentEffect = null;
  2327. }
  2328. private activateTexture(texture: number): void {
  2329. if (this._activeTexture !== texture) {
  2330. this._gl.activeTexture(texture);
  2331. this._activeTexture = texture;
  2332. }
  2333. }
  2334. public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
  2335. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2336. this._gl.bindTexture(target, texture);
  2337. this._activeTexturesCache[this._activeTexture] = texture;
  2338. }
  2339. }
  2340. public _bindTexture(channel: number, texture: WebGLTexture): void {
  2341. if (channel < 0) {
  2342. return;
  2343. }
  2344. this.activateTexture(this._gl.TEXTURE0 + channel);
  2345. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2346. }
  2347. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  2348. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2349. }
  2350. public unbindAllTextures(): void {
  2351. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2352. this.activateTexture(this._gl["TEXTURE" + channel]);
  2353. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2354. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2355. }
  2356. }
  2357. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  2358. if (channel < 0) {
  2359. return;
  2360. }
  2361. this._gl.uniform1i(uniform, channel);
  2362. this._setTexture(channel, texture);
  2363. }
  2364. private _setTexture(channel: number, texture: BaseTexture): void {
  2365. // Not ready?
  2366. if (!texture || !texture.isReady()) {
  2367. if (this._activeTexturesCache[channel] != null) {
  2368. this.activateTexture(this._gl["TEXTURE" + channel]);
  2369. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2370. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2371. }
  2372. return;
  2373. }
  2374. // Video
  2375. var alreadyActivated = false;
  2376. if (texture instanceof VideoTexture) {
  2377. this.activateTexture(this._gl["TEXTURE" + channel]);
  2378. alreadyActivated = true;
  2379. texture.update();
  2380. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  2381. texture.delayLoad();
  2382. return;
  2383. }
  2384. var internalTexture = texture.getInternalTexture();
  2385. if (this._activeTexturesCache[channel] === internalTexture) {
  2386. return;
  2387. }
  2388. if (!alreadyActivated) {
  2389. this.activateTexture(this._gl["TEXTURE" + channel]);
  2390. }
  2391. if (internalTexture.isCube) {
  2392. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2393. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2394. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2395. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2396. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2397. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2398. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2399. }
  2400. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2401. } else {
  2402. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2403. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2404. internalTexture._cachedWrapU = texture.wrapU;
  2405. switch (texture.wrapU) {
  2406. case Texture.WRAP_ADDRESSMODE:
  2407. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2408. break;
  2409. case Texture.CLAMP_ADDRESSMODE:
  2410. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2411. break;
  2412. case Texture.MIRROR_ADDRESSMODE:
  2413. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2414. break;
  2415. }
  2416. }
  2417. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2418. internalTexture._cachedWrapV = texture.wrapV;
  2419. switch (texture.wrapV) {
  2420. case Texture.WRAP_ADDRESSMODE:
  2421. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2422. break;
  2423. case Texture.CLAMP_ADDRESSMODE:
  2424. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2425. break;
  2426. case Texture.MIRROR_ADDRESSMODE:
  2427. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2428. break;
  2429. }
  2430. }
  2431. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2432. }
  2433. }
  2434. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  2435. if (channel < 0) {
  2436. return;
  2437. }
  2438. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2439. this._textureUnits = new Int32Array(textures.length);
  2440. }
  2441. for (let i = 0; i < textures.length; i++) {
  2442. this._textureUnits[i] = channel + i;
  2443. }
  2444. this._gl.uniform1iv(uniform, this._textureUnits);
  2445. for (var index = 0; index < textures.length; index++) {
  2446. this._setTexture(channel + index, textures[index]);
  2447. }
  2448. }
  2449. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  2450. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2451. var value = texture.anisotropicFilteringLevel;
  2452. if (texture.getInternalTexture().samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  2453. value = 1;
  2454. }
  2455. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2456. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2457. texture._cachedAnisotropicFilteringLevel = value;
  2458. }
  2459. }
  2460. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  2461. var data = new Uint8Array(height * width * 4);
  2462. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2463. return data;
  2464. }
  2465. /**
  2466. * Add an externaly attached data from its key.
  2467. * This method call will fail and return false, if such key already exists.
  2468. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2469. * @param key the unique key that identifies the data
  2470. * @param data the data object to associate to the key for this Engine instance
  2471. * @return true if no such key were already present and the data was added successfully, false otherwise
  2472. */
  2473. public addExternalData<T>(key: string, data: T): boolean {
  2474. return this._externalData.add(key, data);
  2475. }
  2476. /**
  2477. * Get an externaly attached data from its key
  2478. * @param key the unique key that identifies the data
  2479. * @return the associated data, if present (can be null), or undefined if not present
  2480. */
  2481. public getExternalData<T>(key: string): T {
  2482. return <T>this._externalData.get(key);
  2483. }
  2484. /**
  2485. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2486. * @param key the unique key that identifies the data
  2487. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2488. * @return the associated data, can be null if the factory returned null.
  2489. */
  2490. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2491. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2492. }
  2493. /**
  2494. * Remove an externaly attached data from the Engine instance
  2495. * @param key the unique key that identifies the data
  2496. * @return true if the data was successfully removed, false if it doesn't exist
  2497. */
  2498. public removeExternalData(key): boolean {
  2499. return this._externalData.remove(key);
  2500. }
  2501. public releaseInternalTexture(texture: WebGLTexture): void {
  2502. if (!texture) {
  2503. return;
  2504. }
  2505. texture.references--;
  2506. // Final reference ?
  2507. if (texture.references === 0) {
  2508. var texturesCache = this.getLoadedTexturesCache();
  2509. var index = texturesCache.indexOf(texture);
  2510. if (index > -1) {
  2511. texturesCache.splice(index, 1);
  2512. }
  2513. this._releaseTexture(texture);
  2514. }
  2515. }
  2516. public unbindAllAttributes() {
  2517. if (this._mustWipeVertexAttributes) {
  2518. this._mustWipeVertexAttributes = false;
  2519. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  2520. this._gl.disableVertexAttribArray(i);
  2521. this._vertexAttribArraysEnabled[i] = false;
  2522. }
  2523. return;
  2524. }
  2525. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2526. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  2527. continue;
  2528. }
  2529. this._gl.disableVertexAttribArray(i);
  2530. this._vertexAttribArraysEnabled[i] = false;
  2531. }
  2532. }
  2533. // Dispose
  2534. public dispose(): void {
  2535. this.hideLoadingUI();
  2536. this.stopRenderLoop();
  2537. // Release scenes
  2538. while (this.scenes.length) {
  2539. this.scenes[0].dispose();
  2540. }
  2541. // Release audio engine
  2542. Engine.audioEngine.dispose();
  2543. // Release effects
  2544. for (var name in this._compiledEffects) {
  2545. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2546. }
  2547. // Unbind
  2548. this.unbindAllAttributes();
  2549. this._gl = null;
  2550. //WebVR
  2551. this.disableVR();
  2552. // Events
  2553. window.removeEventListener("blur", this._onBlur);
  2554. window.removeEventListener("focus", this._onFocus);
  2555. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2556. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2557. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2558. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2559. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2560. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2561. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2562. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2563. }
  2564. // Loading screen
  2565. public displayLoadingUI(): void {
  2566. this._loadingScreen.displayLoadingUI();
  2567. }
  2568. public hideLoadingUI(): void {
  2569. this._loadingScreen.hideLoadingUI();
  2570. }
  2571. public get loadingScreen(): ILoadingScreen {
  2572. return this._loadingScreen;
  2573. }
  2574. public set loadingScreen(loadingScreen: ILoadingScreen) {
  2575. this._loadingScreen = loadingScreen;
  2576. }
  2577. public set loadingUIText(text: string) {
  2578. this._loadingScreen.loadingUIText = text;
  2579. }
  2580. public set loadingUIBackgroundColor(color: string) {
  2581. this._loadingScreen.loadingUIBackgroundColor = color;
  2582. }
  2583. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2584. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2585. }
  2586. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  2587. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2588. }
  2589. public getVertexShaderSource(program: WebGLProgram): string {
  2590. var shaders = this._gl.getAttachedShaders(program);
  2591. return this._gl.getShaderSource(shaders[0]);
  2592. }
  2593. public getFragmentShaderSource(program: WebGLProgram): string {
  2594. var shaders = this._gl.getAttachedShaders(program);
  2595. return this._gl.getShaderSource(shaders[1]);
  2596. }
  2597. // FPS
  2598. public getFps(): number {
  2599. return this.fps;
  2600. }
  2601. public getDeltaTime(): number {
  2602. return this.deltaTime;
  2603. }
  2604. private _measureFps(): void {
  2605. this.previousFramesDuration.push(Tools.Now);
  2606. var length = this.previousFramesDuration.length;
  2607. if (length >= 2) {
  2608. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2609. }
  2610. if (length >= this.fpsRange) {
  2611. if (length > this.fpsRange) {
  2612. this.previousFramesDuration.splice(0, 1);
  2613. length = this.previousFramesDuration.length;
  2614. }
  2615. var sum = 0;
  2616. for (var id = 0; id < length - 1; id++) {
  2617. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2618. }
  2619. this.fps = 1000.0 / (sum / (length - 1));
  2620. }
  2621. }
  2622. private _canRenderToFloatFramebuffer(): boolean {
  2623. if (this._webGLVersion > 1) {
  2624. return this._caps.colorBufferFloat;
  2625. }
  2626. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  2627. }
  2628. private _canRenderToHalfFloatFramebuffer(): boolean {
  2629. if (this._webGLVersion > 1) {
  2630. return this._caps.colorBufferFloat;
  2631. }
  2632. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  2633. }
  2634. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2635. private _canRenderToFramebuffer(type: number): boolean {
  2636. let gl = this._gl;
  2637. //clear existing errors
  2638. while(gl.getError() !== gl.NO_ERROR){}
  2639. let successful = true;
  2640. let texture = gl.createTexture();
  2641. gl.bindTexture(gl.TEXTURE_2D, texture);
  2642. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2645. let fb = gl.createFramebuffer();
  2646. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2647. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2648. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2649. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  2650. successful = successful && (gl.getError() === gl.NO_ERROR);
  2651. //try render by clearing frame buffer's color buffer
  2652. if(successful){
  2653. gl.clear(gl.COLOR_BUFFER_BIT);
  2654. successful = successful && (gl.getError() === gl.NO_ERROR);
  2655. }
  2656. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  2657. if(successful){
  2658. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  2659. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2660. let readFormat = gl.RGBA;
  2661. let readType = gl.UNSIGNED_BYTE;
  2662. let buffer = new Uint8Array(4);
  2663. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  2664. successful = successful && (gl.getError() === gl.NO_ERROR);
  2665. }
  2666. //clean up
  2667. gl.deleteTexture(texture);
  2668. gl.deleteFramebuffer(fb);
  2669. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2670. //clear accumulated errors
  2671. while(!successful && (gl.getError() !== gl.NO_ERROR)) { }
  2672. return successful;
  2673. }
  2674. private _getWebGLTextureType(type: number) : number {
  2675. if (type === Engine.TEXTURETYPE_FLOAT) {
  2676. return this._gl.FLOAT;
  2677. }
  2678. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2679. // Add Half Float Constant.
  2680. return Engine.HALF_FLOAT_OES;
  2681. }
  2682. return this._gl.UNSIGNED_BYTE;
  2683. };
  2684. private _getRGBABufferInternalSizedFormat(type: number) : number {
  2685. if (this._webGLVersion === 1) {
  2686. return this._gl.RGBA;
  2687. }
  2688. if (type === Engine.TEXTURETYPE_FLOAT) {
  2689. return Engine.RGBA32F;
  2690. }
  2691. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  2692. return Engine.RGBA16F;
  2693. }
  2694. return this._gl.RGBA;
  2695. };
  2696. // Statics
  2697. public static isSupported(): boolean {
  2698. try {
  2699. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2700. if (navigator.isCocoonJS) {
  2701. return true;
  2702. }
  2703. var tempcanvas = document.createElement("canvas");
  2704. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2705. return gl != null && !!window.WebGLRenderingContext;
  2706. } catch (e) {
  2707. return false;
  2708. }
  2709. }
  2710. }
  2711. }