我正在尝试创建一个统一缓冲区对象(UBO),我需要用统一填充数组。我目前的做法是使用硬编码结构。
[Serializable,StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MaterialBlock
{
private Vector4 uniform;
};
然后我使用编组从该结构中获取字节数组,并用该数组填充我的 UBO。
public void SetUniformShader(MaterialBlock block, int count) {
int maxSizeMaterialUniformBuffer;
int sizeMaterialBlock = Marshal.SizeOf(typeof (MaterialBlock));
int sizeUniformInstance = sizeMaterialBlock*count;
int uniformInstancesPerBlock;
int numberOfBlocks;
int activeUniformBlocks;
byte[] mtlBuffer;
int uniformBlockIndex;
GL.GetActiveUniformBlock(ProgramId, 0, ActiveUniformBlockParameter.UniformBlockBinding,
out uniformBlockIndex);
GL.GetProgram(ProgramId, ProgramParameter.ActiveUniformBlocks, out activeUniformBlocks);
GL.GetInteger(GetPName.MaxUniformBlockSize, out maxSizeMaterialUniformBuffer);
uniformInstancesPerBlock = maxSizeMaterialUniformBuffer/sizeMaterialBlock;
numberOfBlocks =
(int) Math.Ceiling(((double) sizeUniformInstance/uniformInstancesPerBlock*sizeMaterialBlock));
mtlBuffer = new byte[maxSizeMaterialUniformBuffer];
IntPtr buffer = Marshal.AllocHGlobal(sizeMaterialBlock);
Marshal.StructureToPtr(block, buffer, false);
for (int i = 0; i < uniformInstancesPerBlock; i++) {
Marshal.Copy(buffer, mtlBuffer, i*sizeMaterialBlock, sizeMaterialBlock);
}
Marshal.FreeHGlobal(buffer);
GL.GenBuffers(1, out _iUniform);
GL.BindBuffer(BufferTarget.UniformBuffer, _iUniform);
GL.BufferData(BufferTarget.UniformBuffer, new IntPtr(sizeMaterialBlock), mtlBuffer,
BufferUsageHint.DynamicDraw);
}
我想知道是否有一种更动态的方式来保存统一信息,而不必使用 System.Reflection 来按需创建结构。当我做片段和顶点着色器时,我能够使用一个字符串,然后是 GL.CreateShader() 和 GL.ShaderSource。我能想到的唯一一点是 ShaderType.GeometryShader 实际上是统一着色器,它的标签不同。
任何方法都会受到赞赏,即使这意味着完全不同。如果我遗漏了任何信息,我深表歉意,并会根据要求尝试添加。