gpt4 book ai didi

javascript - 如何从 Javascript/THREE.js 编码和发送 float 据到 GLSL 并解码结果

转载 作者:行者123 更新时间:2023-11-28 06:52:16 27 4
gpt4 key购买 nike

我想对对象位置 (x,y,z) 进行编码并发送到 GLSL 着色器,解码数据,执行一些计算并将结果发送回 CPU。我研究了这个问题并找到了部分答案,例如 decode rgb value to single float without bit-shift in glsl ,但我还没有成功地对结果进行编码和解码。

这是我的代码的一部分。`...

function init() {
...
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
1.0, 1.0
]),
gl.STATIC_DRAW
);

texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

vec1 = new THREE.Vector3(2.6, 3.3, 100.80); //example position vector

data = new Uint8Array([float2Color(vec1.x).r, float2Color(vec1.x).g, float2Color(vec1.x).b, 255, //x
float2Color(vec1.y).r, float2Color(vec1.y).g, float2Color(vec1.y).b, 255, //y
float2Color(vec1.z).r, float2Color(vec1.z).g, float2Color(vec1.z).b, 255 //z
]);
// This encodes to give me int8Array [ 2, 0, 0, 255, 3, 0, 0, 255, 100, 0, 2 more… ]

gl.texImage2D(gl.TEXTURE_2D, level, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}

//render function

function render() {
...
gl.drawArrays(gl.POINTS, 0, 2);
var pixels = new Uint8Array(WIDTH * HEIGHT * 4);
gl.readPixels(0, 0, WIDTH, HEIGHT, gl.RGBA, gl.FLOAT, pixels);
pixels = new Uint8Array(pixels.buffer);

//After getting the results from GLSL, pixels now look like this
//Uint8Array [ 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, … ]



var color = {
r: pixels[0],
g: pixels[1],
b: pixels[2]
};
float1 = decodeVec3ToFloat(color); // I would like to decode and use the data after the position is updated in GLSL
}

function float2Color( f ) {
b = Math.floor(f / 255.0 / 255.0);
g = Math.floor((f - (b * 255.0 * 255.0) ) / 255.0);
// r = Math.floor(f - (b * 255.0 * 255.0) - (g * 255.0) );
r = Math.floor(f % 255);
return {r:r, g:g, b:b};
}

function decodeVec3ToFloat(color) {
var result;
result = color.r * 255.0;
result += color.g * 255.0 * 255.0;
result += color.b * 255.0 * 255.0 * 255.0;
return result;
}

最佳答案

我自己也一直在处理这类事情。您可以使用 DataTextures 来实现此目的,并将它们作为模拟着色器操作的缓冲区传入和传出。 best example我发现到目前为止使用的是过时的 Three.js (v58) 版本,但可以轻松更新。我发现更新脚本然后尝试它直到我对我的用例有足够的理解是很有帮助的。请注意,在示例中,甚至在模拟着色器中传递了固定值,以及在缓冲区中渲染进出的变化的 x、y、z 值。祝你好运!

更新:

我发现我上面使用的旧 THREE.FBOUtils 脚本已被更新和修改,现在称为 THREE.GPUComputationRenderer ——效果很好! (v80)

关于javascript - 如何从 Javascript/THREE.js 编码和发送 float 据到 GLSL 并解码结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854935/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com