babylon.engine.js 128 KB

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