babylon.engine.ts 144 KB

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