2014-10-31 193 views
5

我在寫一個使用javascript和webgl的遊戲引擎。爲了測試它,我寫了一個繪製立方體的程序。爲了這個程序的工作,我必須在調用綁定緩衝區之後調用vertexAttribPointer,但在我調用繪製三角形之前。我想知道這個方法究竟做了什麼,爲什麼我必須按這個順序調用這些方法?vertexAttribPointer的用途是什麼?

我最好的猜測是它初始化屬性,但我不明白爲什麼它必須在客戶端調用,如果是這樣的話。

我已經包括下面的一些來源。一切都是用打字稿寫的。對於完整的源代碼見github.com/dkellycollins/nemesis

設置着色器:

var cubeShader = new shaderProgram(); 
cubeShader.addShader(shaders.colorVertexShader); 
cubeShader.addShader(shaders.colorFragmentShader); 
cubeShader.init(); 
cubeShader.enableAttrib("position", 3, 4 * (3 + 3), 0); 
cubeShader.enableAttrib("color", 3, 4 * (3 + 3), 3 * 4); 

ShaderProgram:

class shaderProgram { 
    constructor() { 
     this.Id = gl.createProgram(); 
    } 

    public Id; 

    public addShader(shader:WebGLShader[]):void { 
     if(shader instanceof Array) { 
      shader.forEach(s => { 
       gl.attachShader(this.Id, s); 
      }); 
     } else { 
      gl.attachShader(this.Id, shader); 
     } 
    } 

    public init():void { 
     gl.linkProgram(this.Id); 
    } 

    public setActive() { 
     gl.useProgram(this.Id); 
    } 

    public enableAttrib(attribName: string, index: number, stride:number, offset: number) { 
     var attrib = gl.getAttribLocation(this.Id, attribName); 
     gl.enableVertexAttribArray(attrib); 
     gl.vertexAttribPointer(attrib, index, gl.FLOAT, false, stride, offset); 
    } 

    public setFloatAttrib(attribName:string, value:number) { 
     var attrib = gl.getAttribLocation(this.Id, attribName); 
     gl.vertexAttrib1f(attrib, value); 
    } 

    public setMatrix(uniName: string, value: number[]) { 
     var uniform = gl.getUniformLocation(this.Id, uniName); 
     gl.uniformMatrix4fv(uniform, false, value); 
    } 
} 

渲染立方體:

public render():void { 
    gl.drawElements(gl.TRIANGLES, this._triangles, gl.UNSIGNED_SHORT, 0); 
} 

頂點着色器來源:

attribute vec3 position; //the position of the point 
uniform mat4 Pmatrix; 
uniform mat4 Vmatrix; 
uniform mat4 Mmatrix; 
attribute vec3 color; //the color of the point 
varying vec3 vColor; 
void main(void) { //pre-built function 
    gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.); //0. is the z, and 1 is w 
    vColor=color; 
} 

回答

8

它告訴WEBGL如何解釋數據:

gl.vertexAttribPointer(attrib, index, gl.FLOAT, false, stride, offset); 

這意味着:對於屬性attrib有是notoffset歸一化開始和在當前綁定gl.ARRAY_BUFFERstridegl.FLOAT類型的index組件。

無論如何,客戶可以自由設置其數據,只要它們可以如上所述。

+0

那麼,爲什麼必須完成屬性?制服不需要這樣做。不應該webgl能夠確定索引,偏移量和步幅,只是從屬性是一個vec3還是我缺少什麼? – dkellycollins 2014-10-31 15:48:05

+1

它將無法找出跨度(完全取決於程序員如何交錯數據,但是緊密排列的缺省值爲0),並且有些人使用半浮點數或整數或短數據(和緩衝區只存儲沒有類型信息的字節序列) – 2014-10-31 15:57:42

+0

我想我現在明白了。我並沒有把所有屬性都從數組緩衝區中獲取數據。感謝您的幫助! – dkellycollins 2014-10-31 20:19:44