opengl:将数组类型加载到统一缓冲区对象



这是我在碎片着色器中的统一块

layout (std140)   uniform Material
{
float array[2];
};

这是统一块对象。我正在使用LWJGL 2.9.3

private UBO(int programID,String blockName)
{
blockID=GL31.glGetUniformBlockIndex(programID,blockName);  //Get index of uniform block

IntBuffer indices=BufferUtils.createIntBuffer(16);
GL31.glGetActiveUniformBlock(programID,blockID,GL31.GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES,indices); //query all the indices of every variable in the uniform block
indices.flip().limit(GL31.glGetActiveUniformBlocki(programID,blockID,GL31.GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS)); //the above method requires an int buffer of 16 even if i dont have 16 variables, but after retriving indices limit the buffer to read only actual number of variables
while(indices.hasRemaining())
{
int variableIndex=indices.get();

String name=GL31.glGetActiveUniformName(programID
,variableIndex
,GL31.glGetActiveUniformsi(programID,variableIndex,GL31.GL_UNIFORM_NAME_LENGTH)); //get the name of the variable

int offset=GL31.glGetActiveUniformsi(programID,variableIndex,GL31.GL_UNIFORM_OFFSET); //query the offset[will use it in buffer sub data]

offsets.put(name,offset);
}


GL15.glBindBuffer(GL31.GL_UNIFORM_BUFFER,bufferID=GL15.glGenBuffers());

GL15.glBufferData(GL31.GL_UNIFORM_BUFFER
,GL31.glGetActiveUniformBlocki(programID,blockID,GL31.GL_UNIFORM_BLOCK_DATA_SIZE)
,GL15.GL_DYNAMIC_DRAW); //allocate buffer to the actual size of the uniform block

GL15.glBindBuffer(GL31.GL_UNIFORM_BUFFER,0);
}

private void bufferData(String name,Buffer value)
{ 
int offset=offsets.get(name); //update float or int arrays
if(value instanceof FloatBuffer){GL15.glBufferSubData(GL31.GL_UNIFORM_BUFFER,offset,(FloatBuffer)value);}
else{GL15.glBufferSubData(GL31.GL_UNIFORM_BUFFER,offset,(IntBuffer)value);}
}

对于常规的非数组变量,它可以很好地工作,但对于数组,float和每个数组类型的值都加载不正确。我已经阅读了指定数组中每个元素都有16[vec4-size]对齐的文档,但我不知道如何在我的代码中指定这一点

要更新浮点数组,我只需使用

bufferData("array[0]",BufferUtils.createFloatBuffer(2).put(new float[]{10.5f,3.0f}).flip());
//the array[0] dosen't actually refer to only the first element of the array it is the name of the array returned by GL31.glGetActiveUniformName()

但是再次,浮子都被错误地加载。

我已经阅读了指定数组中每个元素都有16[vec4-size]对齐的文档,但我不知道如何在我的代码中指定这一点[…]

你是对的,你必须为每个元素添加3个浮动:

BufferUtils.createFloatBuffer(8).put(new float[]{10.5f,0.0f,0.0f,0.0f,3.0f,0.0f,0.0f,0.0f}).flip()

但是,我建议使用单个vec2,而不是float array[2]:

layout (std140)   uniform Material
{
vec2 array;
};

注意,在GLSL中,可以使用Swizzling或索引运算符(例如array[0]array[1](访问矢量数据类型的分量。

最新更新