我可以在像素着色器中生成一个随机数吗? [英] Can I generate a random number inside a pixel shader?

查看:22
本文介绍了我可以在像素着色器中生成一个随机数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个非常简单的着色器,为适用的对象添加随机闪光.我想这样做的方法是向像素着色器中的像素值添加随机的白色阴影 (R = G = B).

I'm trying to write a very simple shader that adds random sparkle to applicable objects. The way I'd like to do this is by adding a random shade of white (R = G = B) to the pixel value within the pixel shader.

似乎 noise() 不像我希望的那样工作:

It seems that noise() doesn't work the way I hope it does:

float multiplier = noise(float3(Input.Position[0], Input.Position[1], time));

它给我错误 X4532:无法将表达式映射到像素着色器指令集"指的是对 noise() 的调用.

It gives me "error X4532: cannot map expression to pixel shader instruction set" referring to the call to noise().

由于我不知道在调用着色器之间保留数字的方法,因此我认为我无法根据渲染前传入的种子编写简单的随机数生成函数.

Since I don't know of a way to retain a number between calls to the shader, I don't think I can just write a simple random number producing function based on a seed passed in before rendering.

有没有办法从像素着色器内部生成随机数?如果有办法,怎么做?

Is there a way to produce a random number from inside a pixel shader? If there is a way, how?

推荐答案

没有什么说你必须从运行到运行重复使用随机生成器的种子,你只需要任何种子.

There's nothing that says you have to reuse the seed for a random generator from run to run, you just need any seed.

如果你使用像素坐标,那么你最终会得到一个确定性的结果(即像素 x、y 将始终具有相同的随机耀斑),但总的来说,它会随机分布整个面部.

If you use, say, the pixel coordinate, then you will end up with a deterministic result (i.e. pixel x, y will always have the same random flare to it), but overall the entire face it will be randomly distributed.

现在,如果你有一些可以根据环境变化的输入(我对像素着色器一无所知),比如像素在场景/相机组合的全局空间中的整体位置而不是相对到多边形本身,那么,特别是在快速移动的环境中,您的结果将有效地随机化.

Now, if you have available as input something that changes based on the environment (I don't really know anything about pixel shaders), like the overall placement of the pixel in the global space of the scene/camera combination than relative to the polygon itself, then, especially in a fast moving environment, your results will effectively random.

如果全局环境中的所有内容恰好完全相同,那么,是的,您将拥有完全相同的随机"分布.但是,如果这些因素中的任何一个发生变化(特别是基于用户输入,这可能是您最动态的噪声源"),那么总体而言,效果可能会足够随机".

If everything in the global environment happens to be exactly the same, then, yes, you will have the exact same "random" distribution. But it any of those factors change (notably based on user input, which it likely you most dynamic "noise source") then overall the effect will be, likely, "random enough".

因此,关键在于您的种子不必是之前运行随机数生成器的结果.它可以是任何东西.因此,根据着色器的输入为您自己的 RNG 设计每个像素的种子可能会给您所需的效果.

So, the key take away is that your seed does not have to be the result of a previous run of the random number generator. It can be anything. So, contriving a seed for each pixel based on inputs to the shader to your own RNG may give you the effect you need.

这篇关于我可以在像素着色器中生成一个随机数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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