javascript - 数组缓冲区不适用于 webgl

标签 javascript webgl arraybuffer

我目前正在尝试将 arraybuffer 与 View 一起使用,将 3 个 float32 (x,y,z) 和 4 个 uint8 (r,g,b,a) 组合成一个数据流,我可以将其传递到我的 web gl申请。

问题是当我使用数组缓冲区时没有任何效果,代码如下:

var buffer = new ArrayBuffer(nbrOfVertices * 16);
var positionView = new DataView(buffer);   

for (var j = 0; j < nbrOfVertices; j++)
{
    positionView.setFloat32((j*16),meshVertexPositions[(j*7)]);
    positionView.setFloat32((j*16)+4,meshVertexPositions[(j*7)+1]);
    positionView.setFloat32((j*16)+8,meshVertexPositions[(j*7)+2]); 
}
gl.bufferData(gl.ARRAY_BUFFER,buffer,gl.STATIC_DRAW);

我知道所有其他代码都是正确的,因为当我改用它时它起作用了:

var buffer = new Float32Array(nbrOfVertices * 4);

for (var j = 0; j < nbrOfVertices; j++)
{
    buffer[(j*4)] = meshVertexPositions[(j*7)];
    buffer[(j*4)+1] = meshVertexPositions[(j*7)+1];
    buffer[(j*4)+2] = meshVertexPositions[(j*7)+2];
}
gl.bufferData(gl.ARRAY_BUFFER,buffer,gl.STATIC_DRAW);

知道为什么我的 arraybuffer 代码(第一个示例)不起作用吗? 只是为了澄清,当我说它不起作用时,我的意思是没有渲染,尽管我在运行它时没有看到任何错误(在 chrome 开发人员控制台或 webgl 检查器中)

最佳答案

您不应为此使用 DataView。你会像这样在同一个缓冲区上使用多个 View

var buffer = new ArrayBuffer(nbrOfVertices * 16);
var floatView = new Float32Array(buffer);
var uint8View = new Uint8Array(buffer);

for (var j = 0; j < nbrOfVertices; ++j) {
  var floatVertexOffset = j * 4;
  floatView[floatVertexOffset + 0] = meshVertexPositions[?? + 0];
  floatView[floatVertexOffset + 1] = meshVertexPositions[?? + 1];
  floatView[floatVertexOffset + 2] = meshVertexPositions[?? + 2];

  var uint8ColorOffset = j * 16 + 12;
  unit8View[uint8ColorOffset + 0] = meshVertexColors[?? + 0];
  unit8View[uint8ColorOffset + 1] = meshVertexColors[?? + 1];
  unit8View[uint8ColorOffset + 2] = meshVertexColors[?? + 2];
  unit8View[uint8ColorOffset + 3] = meshVertexColors[?? + 3];
}

您不使用 DataView 的原因是您需要 GPU 数据的 native 浮点和 RGBA 格式。 DataView 用于以特定字节序格式读取/写入数据,而不管 native 平台的字节序。

换句话说,如果您使用 DataView,您最终会向 GPU 上传错误类型的数据。您使用 DataView 读取 native 格式或将 native 数据转换为特定的二进制格式。

关于javascript - 数组缓冲区不适用于 webgl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537721/

相关文章:

webgl - 如何通过 WebGL 使用 OpenGL 4 功能

javascript - Javascript 和一般情况下的按位运算符

javascript - Html DOM 到数组缓冲区来为 pdf 制作 BLOB?

javascript - Espresso 是否有任何 "sugars"可以为 javascript 编辑添加大括号/方括号突出显示?

javascript - 将数组插入 JSON 对象、Javascript

javascript - 使用 Google 的 Closure 排除库的模块

arrays - WebGL 传递数组着色器

webgl - 使用单个顶点缓冲区还是多个?

javascript - XMLHTTP Post 不起作用

javascript错误: this.节点为空或不是对象