如何用鼠标拖动对象? (OpenGL的)

时间:2017-12-01 14:27:47

标签: c++ opengl glfw picking drag

我读了很多材料来用鼠标拖动对象并将它们应用到我的项目中...... 但它仍然无效。 即使是gluUnproject的结果似乎也是不正确的。 (我用模板缓冲区来索引)

渲染循环

while (!glfwWindowShouldClose(window))
{
    glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
    glClearStencil(0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glEnable(GL_STENCIL_TEST);
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    /*
    for (int i = 0; i < 1; i++)
    {
        glStencilFunc(GL_ALWAYS, i + 1, -1);

    }*/
    glStencilFunc(GL_ALWAYS, 1, -1);
    camA.renderCamera(cube.cShader.program);
    cube.RenderCube();
    glStencilFunc(GL_ALWAYS, 2, -1);
    camA.renderCamera(cube2.cShader.program);
    cube2.RenderCube();

    if (sMod == 1)
    {
        pick.moveObj(Xpos, Ypos);
        camA.mModelMat = glm::translate(camA.mModelMat, glm::vec3(pick.moveX, pick.moveY, pick.moveZ));
    }

    //swap buffers
    glfwSwapBuffers(window);

    //window event
    glfwPollEvents();
}

采摘的一部分

void Pick::moveObj(int x, int y)
{
int window_width = 800; int window_height = 800;

glReadPixels(x, window_height - y - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

printf("Clicked on pixel %d, %d, depth %f, stencil index %u\n", x, y, depth, index);

glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, proj);
glGetIntegerv(GL_VIEWPORT, view);

gluUnProject(x, window_height - y -1, 0, model, proj, view, &objX, &objY, &objZ);
printf("to 0  // X :  %d, Y : %d, Z : %d \n", objX, objY, objZ);
gluUnProject(x, window_height - y - 1, 1, model, proj, view, &objX, &objY, &objZ);
printf("to 1  // X :  %d, Y : %d, Z : %d", objX, objY, objZ);



moveX = (float)(objX - PobjX);
moveY = (float)(objY - PobjY);
moveZ = (float)(objZ - PobjZ);
}

顶点着色器

#version 330 core

layout (location = 0) in vec3 pos;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

void main()
{
gl_Position = proj * view * model * vec4(pos.xyz, 1.0);
}

命令窗口(单击并移动鼠标按钮时)

enter image description here

你可以告诉我我的代码有什么问题吗?

0 个答案:

没有答案