World position to gl_PrimitiveID

Hello to the group,

My question is if I can translate a world position to the nearest gl_PrimitiveID in fragment shader so that I can color a face of the mesh?

gl_PrimitiveID is just an index given to each primitive. It has nothing to do with positions of vertices or primitives.

If you know what triangle you want to manipulate, you can figure out what primitive ID it will get (by counting the triangles in the rendering command) and provide that index to the shader (via a uniform or somesuch).

Thanks for the answer. Let me rephrase the question, how can I get the nearest vertex if given a world position (The world position will be “touching” the mesh)? And second step is how to count the triangles in the rendering command to find the gl_PrimitiveID that contains this vertex? What I am trying to achieve is color the face that is nearest to the world position.

Iterate through the vertices, calculating the distance of each one from the specified position, and keeping track of the closest vertex so far and its distance.

Iterate through the index array until you find the ID of the target vertex.

You’re not going to be doing any of this in a fragment shader. This is all CPU collision-detection work. And to make it reasonably efficient, you’re going to have to build mesh data designed specifically to detect such things. Meshes stored in an efficient way to render with are not store efficiently for the purposes of doing collision detection.

Also, I’d recommend not bothering with using primitive IDs to color the triangle. What you should do is render the mesh normally, then render just the identified triangle with the different color, overwriting what was previously written.

Thank you both for the replies. Although your solutions look good and correct I think there is a lot of overhead for the needs of the application. What I ended up doing is passing the contact point as a uniform to the fragment shader and getting the distance with the current fragment. If it is less than a certain distance I color the fragment position. This results in multiple faces being colored (and some of them partially) which is not exactly what we need but it is faster than looking up a bunch of stuff to pass all the information to the shaders. Thanks again for your time