DirectX计算着色器:如何编写具有可变数组大小参数的函数? [英] DirectX compute shader: how to write a function with variable array size argument?

查看:115
本文介绍了DirectX计算着色器:如何编写具有可变数组大小参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在计算着色器(HLSL)中编写一个函数,该函数接受参数为大小不同的数组.编译器总是拒绝它.

I'm trying to write a function within a compute shader (HLSL) that accept an argument being an array on different size. The compiler always reject it.

示例(不起作用!):

void TestFunc(in uint SA[])
{
   int K;
   for (K = 0; SA[K] != 0; K++) {
       // Some code using SA array
   }
}

[numthreads(1, 1, 1)]
void CSMain(
    uint S1[] = {1, 2, 3, 4 };  // Compiler happy and discover the array size
    uint S2[] = {10, 20};  // Compiler happy and discover the array size

    TestFunc(S1);
    TestFunc(S2);
}

如果我在TestFunc()中给出一个数组大小,则编译器在调用TestFunc()并传递该特定数组大小但拒绝其他大小的调用时感到很高兴.

If I give an array size in TestFunc(), then the compiler is happy when calling TestFunc() passing that specific array size but refuse the call for another size.

推荐答案

您不能使用不确定大小的函数参数. 您需要初始化一个已知长度的数组,以及一个保存该数组长度的int变量.

You cannot have function parameters of indeterminate size. You need to initialize an array of know length, and an int variable that holds the array length.

void TestFunc(in uint SA[4], in uint saCount) 
{  int K; 
   for (K = 0; SA[K] != 0; K++)
     { 
        // Some code using SA array, saCount is your array length;
      }
 }

[numthreads(1, 1, 1)] 
 void CSMain()
{
 uint S1count = 4;
 uint S1[] = {1, 2, 3, 4 };
 uint S2count = 2;
 uint S2[] = {10, 20,0,0}; 
 TestFunc(S1, S1count); 
 TestFunc(S2, S2count);
 }

在我的示例中,我将数组的最大大小设置为4,但是可以根据需要将其设置为更大.您还可以为不同的数组长度设置多个功能,如果数据超出数组最大大小,则可以设置多个遍次.

In my example I have set your array max size as 4, but you can set it bigger if needed. You can also set multiple functions for different array lengths, of set up multiple passes if your data overflows your array max size.

编辑以回答评论 问题在于,在编译器错误状态下,函数参数的数组维必须明确.这是无法避免的.但是,您可以做的是完全避免传递数组.如果将TestFunc内联到CSMain中,则可以避免传递数组,并且例程可以编译和运行.我知道它可以使您的代码更长且更难维护,但这是使用未指定长度的数组执行所需操作的唯一方法.好处是,通过这种方式,您可以访问array.Length,这可能会使您的代码更简单.

Edit to answer comment The issue is that array dimensions of function parameters must be explicit as the compiler error states. This cannot be avoided. What you can do however, is avoid passing the array at all. If you in-line your TestFunc in your CSMain, you avoid passing the array and your routine compiles and runs. I know it can make your code longer and harder to maintain, but it's the only way to do what you want with an array of unspecified length. The advantage is that this way you have access to array.Length that might make your code simpler.

这篇关于DirectX计算着色器:如何编写具有可变数组大小参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆