DirectCompute atomic counter
Asked Answered
C

1

7

In a compute shader (with Unity) I have a raycast finding intersections with mesh triangles. At some point I would like to return how many intersections are found.

I can clearly see how many intersections there are by marking the pixels, however if I simply increment a global int for every intersection in the compute shader (and return via a buffer), the number I get back makes no sense. I assume this is because I'm creating a race condition.

I see that opengl has "atomic counters" : https://www.opengl.org/wiki/Atomic_Counter, which seem like what I need in this situation. I have had no luck finding such a feature in either the Unity nor the DirectCompute documentation. Is there a good way to do this?

I could create an appendBuffer, but it seems silly as I literally need to return just a single int.

Condescend answered 20/2, 2015 at 21:44 Comment(0)
C
7

HA! That was easy. I'll leave this here just in-case someone runs into the same problem. HLSL has a whole set of "interlocked" functions that prevent this sort of thing from happening:

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476334(v=vs.85).aspx

In my case it was:

InterlockedAdd(collisionCount, 1);

To replace

collisionCount++;

And that's it!

Condescend answered 20/2, 2015 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.