我正在嘗試爲我的2D遊戲引擎重寫基於畫布的渲染。我已經取得了很好的進展,並且可以很好地將紋理渲染到webgl上下文中,並通過縮放,旋轉和混合來完成。但我的表現很糟糕。在我的測試筆記本電腦上,我可以一次獲得屏幕上1000個實體的香草2d畫布中的30 fps;在WebGL中,我在屏幕上獲得了500個實體的30 fps。我期望的情況是相反的!在WebGL中批量調用的最快方式
我有一個偷偷摸摸的嫌疑,罪魁禍首是這一切Float32Array
緩衝區垃圾,我在折騰。這裏是我的渲染代碼:
// boilerplate code and obj coordinates
// grab gl context
var canvas = sys.canvas;
var gl = sys.webgl;
var program = sys.glProgram;
// width and height
var scale = sys.scale;
var tileWidthScaled = Math.floor(tileWidth * scale);
var tileHeightScaled = Math.floor(tileHeight * scale);
var normalizedWidth = tileWidthScaled/this.width;
var normalizedHeight = tileHeightScaled/this.height;
var worldX = targetX * scale;
var worldY = targetY * scale;
this.bindGLBuffer(gl, this.vertexBuffer, sys.glWorldLocation);
this.bufferGLRectangle(gl, worldX, worldY, tileWidthScaled, tileHeightScaled);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
var frameX = (Math.floor(tile * tileWidth) % this.width) * scale;
var frameY = (Math.floor(tile * tileWidth/this.width) * tileHeight) * scale;
// fragment (texture) shader
this.bindGLBuffer(gl, this.textureBuffer, sys.glTextureLocation);
this.bufferGLRectangle(gl, frameX, frameY, normalizedWidth, normalizedHeight);
gl.drawArrays(gl.TRIANGLES, 0, 6);
bufferGLRectangle: function (gl, x, y, width, height) {
var left = x;
var right = left + width;
var top = y;
var bottom = top + height;
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
left, top,
right, top,
left, bottom,
left, bottom,
right, top,
right, bottom
]), gl.STATIC_DRAW);
},
bindGLBuffer: function (gl, buffer, location) {
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
},
這是我的簡單測試着色器(這些缺失混合,縮放旋轉&):
// fragment (texture) shader
precision mediump float;
uniform sampler2D image;
varying vec2 texturePosition;
void main() {
gl_FragColor = texture2D(image, texturePosition);
}
// vertex shader
attribute vec2 worldPosition;
attribute vec2 vertexPosition;
uniform vec2 canvasResolution;
varying vec2 texturePosition;
void main() {
vec2 zeroToOne = worldPosition/canvasResolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
texturePosition = vertexPosition;
}
如何獲得更好的性能,任何想法?有沒有辦法批量我的drawArrays?有沒有辦法減少緩衝垃圾?
謝謝!
爲了吸引更多的intested我建議你題爲你的問題,如「在WebGL上批量drawArrays的最快方法」 – 2013-03-22 15:54:40
@Mikko完成。謝謝! – 2013-03-22 19:32:28
@AbrahamWalters:您是否爲每個框架的每個實體運行確切的呈現代碼? (又名500 * 30 = 1500次/秒)如果是這樣,我認爲如果你讓它坐在那裏,標籤/瀏覽器在一個小時內(如果不是十分鐘)就會耗盡內存。 – 2013-03-22 23:01:51