gpt4 book ai didi

GLSL channel 选择

转载 作者:行者123 更新时间:2023-12-05 01:48:06 27 4
gpt4 key购买 nike

我有一个 GLSL 着色器,它从输入纹理的 channel 之一(例如 R)读取,然后写入输出纹理中的同一 channel 。该 channel 必须由用户选择。

我现在能想到的就是使用一个 int 制服和大量的 if 语句:

uniform sampler2D uTexture;
uniform int uChannelId;
varying vec2 vUv;

void main() {

//read in data from texture
vec4 t = texture2D(uTexture, vUv);
float data;
if (uChannelId == 0) {
data = t.r;
} else if (uChannelId == 1) {
data = t.g;
} else if (uChannelId == 2) {
data = t.b;
} else {
data = t.a;
}

//process the data...
float result = data * 2; //for example

//write out
if (uChannelId == 0) {
gl_FragColor = vec4(result, t.g, t.b, t.a);
} else if (uChannelId == 1) {
gl_FragColor = vec4(t.r, result, t.b, t.a);
} else if (uChannelId == 2) {
gl_FragColor = vec4(t.r, t.g, result, t.a);
} else {
gl_FragColor = vec4(t.r, t.g, t.b, result);
}

}

有没有什么方法可以像 t[uChannelId] 这样的字典访问?

或者也许我应该有 4 个不同版本的同一个着色器,每个版本处理不同的 channel ,这样我就可以避免所有的 if 语句?

执行此操作的最佳方法是什么?

编辑:更具体地说,我正在使用 WebGL (Three.js)

最佳答案

有这样一种方法,而且很简单,你在题中实际写了就可以了。只需使用 t[channelId]。引用GLSL Spec (这来自版本 3.30,第 5.5 节,但也适用于其他版本):

Array subscripting syntax can also be applied to vectors to provide numeric indexing. So in

vec4 pos;

pos[2] refers to the third element of pos and is equivalent to pos.z. This allows variable indexing into a vector, as well as a generic way of accessing components. Any integer expression can be used as the subscript. The first component is at index zero. Reading from or writing to a vector using a constant integral expression with a value that is negative or greater than or equal to the size of the vector is illegal. When indexing with non-constant expressions, behavior is undefined if the index is negative, or greater than or equal to the size of the vector.

请注意,对于代码的第一部分,您使用它来访问纹理的特定 channel 。您也可以使用 ARB_texture_swizzle功能。在这种情况下,您只需使用一个固定的 channel ,比如 r,在着色器中进行访问,然后调整实际的纹理 channel ,以便您要访问的所有 channel 变为 r.

更新:由于目标平台原来是webgl,所以这些建议不可用。然而,一个简单的解决方案是使用 vec4 uniform 代替 uChannelID,所选组件为 1.0,所有其他组件为 0.0。假设此变量称为 uChannelSel。您可以在第一部分使用 data=dot(t, uChannelSel),在第二部分使用 gl_FragColor=(vec4(1.0)-uChannelSel) * t + uChannelSel*result .

关于GLSL channel 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903926/

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