OpenGL中的颜色编码拾取问题
我正在为我的一个班级项目制作一款游戏,实际上是《我的世界》的一个非常基本的复制品。我现在陷入了拾取过程,这将使我能够在游戏环境中销毁和创建块。
我一直在尝试使用 OpenGL 自己的拾取模式,但没有成功,并且使用数学库构建我自己的光线拾取器对于这种规模的项目来说似乎是一项艰巨的工作。因此,我决定使用颜色编码拾取方法,该方法包括以不同的颜色渲染每个可拾取对象,然后获取鼠标位置的颜色并使用它来识别拾取的对象。
我当前的界面只是许多堆叠的盒子的 3D 渲染,创建了一个类似地形的结构。由于我还没有完成纹理映射,因此所有框都是灰色阴影(启用照明)。
现在,是一些实际代码的时候了:
这是初始化部分,启用纹理、照明等。
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
单击鼠标按钮时,我尝试通过以下方式获取鼠标光标位置(实际上总是在窗口中间)的颜色:
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glDisable(GL_DITHER);
glDisable(GL_LIGHT0);
glDisable(GL_LIGHT1);
renderColors();
GLubyte pixels[3];
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, (void *)pixels);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glEnable(GL_DITHER);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
问题是,禁用不起作用,我总是在 pixels
数组中获取不同灰度的 RGB 值。
可能是什么问题?
I am making a game, actually a very basic replica of Minecraft, for a class project of mine. I'm stuck in the picking process right now, which would enable me to destroy and create blocks in the game environment.
I've been trying to use OpenGL's own picking mode without any success, and building my own ray picker using math libraries seems to large a work for a project of this size. So, I've decided to use the color coded picking method, which consists of rendering every pickable object in a different color, then getting the color at the mouse position and using it to identify the picked object.
My current interface is just a 3D rendering of many boxes stacked, creating a terrain-like structure. Since I've done no texture mapping yet, all the boxes are shades of grey (lighting enabled).
Now, time for some actual code:
This is the initialization part, enabling texturing, lighting etc.
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
When a mouse button is clicked, I try to get the color at the mouse cursor's position (always the middle of the window, actually) by:
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glDisable(GL_DITHER);
glDisable(GL_LIGHT0);
glDisable(GL_LIGHT1);
renderColors();
GLubyte pixels[3];
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, (void *)pixels);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glEnable(GL_DITHER);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
Problem is, the disables do not work and I always get the RGB values of different shades of grey in my pixels
array.
What could be the problem?
也许您忘记清除颜色缓冲区并禁用深度缓冲区,并且所有渲染的颜色都会导致 Z-Fighting 或根本不渲染(如果 z-test 为“较少”)。尝试添加交换缓冲区代码并查看在 ColorRender 代码之后渲染的内容。
Perhaps you forget to clear the color buffer and disable depth buffer and all your rendered colors are causing Z-Fighting or not rendered at all (if z-test is "less"). Try to add swapbuffers code and see what gets rendered after your ColorRender code.