gl-aliased-vao
Version:
like vao, but only for simple vertex arrays
87 lines (76 loc) • 2.64 kB
JavaScript
function getAttributeLocation(name, shader) {
if (!name)
return null
var attr = shader.attributes
if (attr[name])
return attr[name].location
return null
}
var nattribs = null
var bound = null
function doBind(gl, elements, attributes, shader) {
if (elements) {
elements.bind()
} else {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
}
if (nattribs === null) {
nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS) | 0
bound = new Array(nattribs)
}
if (attributes) {
if (attributes.length > nattribs) {
throw new Error("gl-vao: Too many vertex attributes")
}
var lastBound = null
for (i=0; i<nattribs; i++)
bound[i] = false
//now bind aliased attributes
for (i=0; i<attributes.length; i++) {
var attrib = attributes[i]
var loc = getAttributeLocation(attrib.name, shader)
if (loc === null)
continue
bound[loc] = true
if(attrib.buffer) {
var buffer = attrib.buffer
var size = attrib.size || 4
var type = attrib.type || gl.FLOAT
var normalized = !!attrib.normalized
var stride = attrib.stride || 0
var offset = attrib.offset || 0
if (lastBound !== buffer) {
buffer.bind()
lastBound = buffer
}
gl.enableVertexAttribArray(loc)
gl.vertexAttribPointer(loc, size, type, normalized, stride, offset)
} else {
if(typeof attrib === "number") {
gl.vertexAttrib1f(loc, attrib)
} else if(attrib.length === 1) {
gl.vertexAttrib1f(loc, attrib[0])
} else if(attrib.length === 2) {
gl.vertexAttrib2f(loc, attrib[0], attrib[1])
} else if(attrib.length === 3) {
gl.vertexAttrib3f(loc, attrib[0], attrib[1], attrib[2])
} else if(attrib.length === 4) {
gl.vertexAttrib4f(loc, attrib[0], attrib[1], attrib[2], attrib[3])
} else {
throw new Error("gl-vao: Invalid vertex attribute")
}
gl.disableVertexAttribArray(loc)
}
}
for (i=0; i<nattribs; i++) {
if (!bound[i])
gl.disableVertexAttribArray(i)
}
} else {
gl.bindBuffer(gl.ARRAY_BUFFER, null)
for(var i=0; i<nattribs; ++i) {
gl.disableVertexAttribArray(i)
}
}
}
module.exports = doBind