GLSL:如何执行类似 switch 的语句

use*_*858 3 shader glsl

我想根据传递到着色器的数据动态调用缓动。所以用伪代码来说:

var easing = easings[easingId]
var value = easing(point)
Run Code Online (Sandbox Code Playgroud)

我想知道在 GLSL 中完成此任务的最佳方法。我可以以某种方式使用 switch 语句,或者可以将缓动放入数组中并像这样使用它们。或者也许有一种方法可以创建哈希表并像上面的示例一样使用它。

easingsArray = [
  cubicIn,
  cubicOut,
  ...
]

uniform easingId

main() {
  easing = easingsArray[easingId]
  value = easing(point)
}
Run Code Online (Sandbox Code Playgroud)

这将是潜在的阵列方法。另一种方法是 switch 语句。也许还有其他人。想知道推荐的方法是什么。也许我可以以某种方式使用一个结构......

小智 9

如果您需要在 GLSL 中进行条件分支(在您的情况下基于变量选择缓动函数),您将需要使用 if 或 switch 语句。

例如

if (easingId == 0) {
    result = cubicIn();
} else if (easingId == 1) {
    result = cubicOut();
}
Run Code Online (Sandbox Code Playgroud)

或者

switch (easingId) {
case 0:
    result = cubicIn();
    break;
case 1:
    result = cubicOut();
    break;
}
Run Code Online (Sandbox Code Playgroud)

GLSL 不支持函数指针,因此您正在考虑的那种动态调度解决方案(函数指针表等)不幸的是不可能的。

虽然您的问题明确涉及传递到着色器的数据,但我还想指出,如果控制分支的值作为统一传递到着色器,那么您可以编译着色器的多个变体,然后从应用程序本身动态选择正确的一个(即使用正确的缓动函数的)。这将节省着色器中分支的成本。