I am writing a game engine using javascript and webgl. To test this, I wrote a program that draws a cube. For this program to work, vertexAttribPointer must be called after I call the binding buffers, but before I call draw triangles. I was wondering what exactly this method did and why should I call these methods in that order?
My best guess is that it initializes the attribute, but I donβt understand why it needs to be called on the client side, if so.
I have a part of the source below. Everything is written in typescript. Full source see github.com/dkellycollins/nemesis
Shader Setup:
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); } }
Rendering a cube:
public render():void { gl.drawElements(gl.TRIANGLES, this._triangles, gl.UNSIGNED_SHORT, 0); }
Vertex Shader Source:
attribute vec3 position;