Sse
Sse

Reputation: 1

How to drag an object by the mouse? (opengl)

I read a lot of materials to drag an object by the mouse and applied them to my project... But it still doesn't work. Even the result of gluUnproject seems uncorrect. (I used stencil buffer to index)

rendering loop

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();
}

part of picking

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);
}

vertex shader

#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);
}

command window (when mouse button clicked&moved)

enter image description here

could you please tell me what's wrong with my code?

Upvotes: 0

Views: 974

Answers (0)

Related Questions