babylon.engine.ts 143 KB

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