D3D11:HLSL中可变数量的灯 [英] D3D11: variable number of lights in HLSL

查看:74
本文介绍了D3D11:HLSL中可变数量的灯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++和Direct3D11开发游戏引擎,现在我想向场景中添加可变数量的灯光.到目前为止,我设法添加并渲染了着色器程序中已知并已编码的简单灯光.

I'm working on a game engine in C++ and Direct3D11 and I want now to add a variable number lights to the scene. Up to date, I managed to add and render simple lights of a count that was already known and coded in the shader programs.

在shader.fx中:

In shader.fx:

static const int LightsCount= 4;

struct NF3D_LIGHT
{
    // Members...
};

cbuffer Light : register(b5)
{
    NF3D_LIGHT light[LightsCount];
};

...

// And the pixel shader function:
float4 PS(PS_INPUT input) : SV_Target
{
    for(int i = 0; i < LightsCount; i++)
    {
        // Process each light and return the final pixel colour
    }
}

这很好用.但是,如果我尝试:

And this works fine. But if I try to:

cbuffer LIGHTS_COUNT : register(b13)
{
    int LightsCount;
}

要根据游戏中发生的变化来改变灯光的数量,这是行不通的.我知道我可以在应用程序开始时给 LightsCount 一个大值,然后向数组中添加灯光,但是我发现此方法复杂,固定且效率不高.

to make the number of lights vary according to what is happening in the game, this does not work. I know I could give LightsCount a big value right at the beginning of the application and add lights to the array but I find this method complicated, fixed and not efficient.

有人知道如何解决这个问题吗?预先谢谢你.

Does anybody know how to solve this problem? Thank you in advance.

推荐答案

从着色器访问可变大小数组(具有运行时定义的大小)的一般问题可能会有所不同,具体取决于数组大小,数据更改的频率和您要定位的硬件.

The general problem of accessing a variable size array (with runtime defined size) from shader might be solved differently, depending on array size, frequency of data changes and hardware you are targeting.

想到了几种技术:

  1. 如果您的数组很小,那么最简单的方法就是按照您的建议传递一个带有固定大小数组当前大小的常量缓冲区.

几乎可以在任何硬件上使用的方法是将数据写入纹理从着色器加载.您只能读取基本类型( float float4 等),因此您需要对纹理实施适当的索引以读取复杂的对象(struct s).

The way that will work on virtually any hardware is to write data into a texture and Sample or Load it from shader. You can only read primitive types (float, float4, etc.), so you'll need to implement proper indexing into a texture to read out complex objects (structs).

在Shader Model 5硬件(以及某些SM 4上)上,您可以使用 StructuredBuffer s可以从缓冲区读取结构化数据.

On Shader Model 5 hardware (and on some SM 4 too) you can use UAVs and StructuredBuffers to read structured data from buffers.

如果您具有涉及数组的非常复杂的计算,并且如果目标硬件允许这样做,则可能需要将处理移至Compute Shader或什至OpenCL或CUDA内核.

If you have really complex computations that involve arrays, and if target hardware allows you to do so, you might want to move processing to either Compute Shader or even to OpenCL or CUDA kernel.

考虑到给定的问题,即经典照明,我想说我所见的99%使用方法1.无论如何,您实际上在大多数情况下在一个场景中实际上并没有十多个照明.

Considering given problem, which is classic lighting, I would say that 99% of what I've seen use method 1. You don't really have more than a dozen of lights in a scene most of the time anyway.

这篇关于D3D11:HLSL中可变数量的灯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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