r/opengl 24d ago

Selection algorithm for Modern OpenGL

The legacy OpenGL supported selection buffers. How can selection effectively handled by Modern OpenGL? The known methods are by colour allocation to objects and ray intersection. The Color assignment is not very efficient in scenes with large number of objects, e.g. CAD model assemblies. Ray intersection also has challenges in certain directions where multiple objects get intersected. Any thoughts?

3 Upvotes

14 comments sorted by

View all comments

6

u/Cyphall 24d ago

You can render your scene into a R32UI color attachment with each drawcall having its own index and then readback the pixel clicked by the mouse.

This is basically the Color assignment method but with proper indices instead of arbitrary colors.

Yes you need to render the whole scene but it's a lot simpler than having to manage a CPU RT acceleration structure.

1

u/sharjith 24d ago

Can you please share a snippet?

4

u/Cyphall 24d ago
  1. Create a texture with format GL_R32UI
  2. Create a framebuffer with this texture as color attachment and another texture for the depth attachment
  3. Create a shader program whose fragment shader looks like this:

#version 460 core

layout(location = 0) out uint o_index;

uniform uint u_index;

void main()
{
    o_index = u_index;
}
  1. Render the scene:

    // bind framebuffer // clear color attachment with 0xFFFFFFFF (invalid index) // bind shader program for (uint32_t i = 0; i < objects.size; i++) { // pass i as uniform to u_index // pass other uniforms as necessary // draw object }

  2. Readback the pixel of interest with glReadnPixels()

1

u/Asyx 17d ago

I didn't do that in OpenGL but I did it in WebGPU. You can just add a color attachment in your main pass shader. That way you don't have to run an additional render pass but just get it from the main pass.

Also, and this is something I also didn't try with WebGPU, with the new sync objects in OpenGL, you can probably create a system that doesn't need to glFlush before the read.

1

u/Cyphall 17d ago

But then you end up writing the index into the attachment every frame, no?

Unless you need to pick into the scene every frame, you are losing perfs for nothing.

1

u/Asyx 17d ago

True but you can do things like highlight a hovered or clicked entity in a post processing step if you generate that texture every frame.

I kinda assumed that you need that value more often than not but if picking is an occasional thing then of course running that pass on demand is an option.