I have a compute shader which simulates some fluid as particle. Particles are read from a buffer. Each particle is handled in one thread. During the execution of the thread, one particle moves its uv position and adds to pixel of a UAV named Water . Therefore each thread leaves a trail of its movement on the Water texture.
_watTx[texID] += watAddition * cellArea.x;
The problem is there are lots of particles moving around and most often multiples are present at the same texID
. It seems there is a race condition since every time I run the simulation the results are slightly different. Is there a way to enforce mutual exclusion so the writes do not happen at the same time and the results become predictable?
答案 0 :(得分:0)
我找到了解决此问题的方法。 InterlockedAdd以原子方式添加到像素。但它仅适用于int
和unit
无人机。
在我的情况下,值是浮点值,但范围非常有限(如0到10)。所以解决方案是使用int
无人机。我们将计算结果乘以一个巨大的数字(如10000),然后写入无人机:
InterlockedAdd(_watTx[texID], (watAddition * cellArea.x * 10000));
结果的精度为0.0001,在我的情况下完全没问题。在另一个像素或计算着色器中,我们可以将int UAV中的值乘以0.0001并写入所需的浮点渲染目标。
此过程消除了并发写入问题,并且每次运行的结果都相同。