微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

glsl - 我可以将常量传递给函数而不将常量处理到参数中吗?

如何解决glsl - 我可以将常量传递给函数而不将常量处理到参数中吗?

我有一个 glsl 函数,它可以接受几个 const 数组之一,并使用该数组中的信息执行一些操作。例如:

const uint A[] = { /* 10 values here */ };
const uint B[] = { /* 10 different values here */ };
const uint C[] = { /* 10 different values here */ };

float doSomethingWithArray(const uint arr[10],float x){
  // do some operations which use the constant array and a non-constant value. Eg:
  uint a = arr[floor(x)];
  uint b = arr[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}

如果我调用这个函数,将其中一个常量数组作为参数 doSomethingWithArray(A,5.0) 传递,我担心这些数组会被复制到参数中,从而减慢程序速度。

https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Parameters

传递给函数的值在函数调用时被复制到参数中

这让我觉得拥有 3 个单独的函数会更快,每个函数使用不同的常量数组。这样,就不必复制数组。例如:

float doSomethingWithA(float x){
  uint a = A[floor(x)];
  uint b = A[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}
float doSomethingWithB(float x){
  uint a = B[floor(x)];
  uint b = B[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}
float doSomethingWithC(float x){
  uint a = C[floor(x)];
  uint b = C[a] * 2 + 3;
  float c = (b + a) * x;
  return c;
}

然而,这会导致大量重复代码,尤其是在有更多常量数组的情况下。有没有办法在不复制数组且不重复代码的情况下执行此操作?

我正在使用 glslc 编译为 .spv。

解决方法

不使用 Vulcan,因为我的 gfx 卡不支持它,但在 GLSL 中我可以随意使用我可以使用宏来代替这样的功能:

#define doSomethingWithArray(arr,x) ((arr[arr[floor(x)]] * 2 + 3 + arr[floor(x)]) * x)

宏将为您硬编码这 3 个实例......这里是一个示例(片段着色器):

#version 420 core
out layout(location=0) vec4 col;
#define test(arr,x) ((arr[arr[int(floor(x))]] * 2 + 3 + arr[int(floor(x))]) * x)
const uint A[]={0,1,2,3,4,5,6,7,8,9};
const uint B[]={1,9,0};
const uint C[]={2,1};
void main()
    {
    float x=3.75;
    col=vec4(test(A,x),test(B,test(C,1.0);
    }

#version 420 core 是第一个不会对您在我的 nVidia 上使用的内容(如常量数组等)抛出大量警告和错误的版本

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。