How do Distance Fields work in materials?

So I want to use the material expressions “DistanceFieldGradient” and “DistanceToNearestSurface”.
They work great straight out of the box, except one minor detail.
There are some gradients and artifacts and I have no clue where they come from and how to remove them.

First the “DistanceToNearestSurface” :

The intersection of the cube with the floor(a cube as well) is noticeable. But why are the sides red where no other surface is near or even intersecting?
The material for the cube is an exact copy of the one that can be [found in the documentation][2].

The generated distance fields look good as far as I can tell.

Something similar but not the exact same is happening with “DistanceFieldGradient”:

Again the intersection is noticeable but kind of very difficult to use with those other gradients overlapping them.
On more complex meshes they are all over the place.

The material setup is quite simple:

Any suggestions where they come from and how I can get rid of them?

So from my limited knowledge, I have found that using this on a plane actually does work, so it seem that your mesh is interacting on itself and nulling out the effect where the sides meet. Someone correct me if I’m wrong, please.

You’re correct. The material is sampling the distance field (some kind of 3D Texture) and therefor it cannot detect what objects it is sampling. That would require a seperate distance field texture for each object and that would have a quite noticable effect on performance.

So in fact these are no atrifacts or errors. This is the way it should behave and as you can see it is doing so very well.

A workaround to prevent an object from sampling itself is to multiply the vertex normal by some amount and add it to AbsoluteWorldPosition. Put that into the position input of either of the two nodes. This will reduce the precision quite a bit but at least the object is not sampling itself anymore.

75600-distancefieldoffset.png

I found this workaround somewhere in the forums I think but unfortunately I can’t find the thread anymore.

Hope this helps.

6 Likes