GLFW: input & timeGLFW 3.0

glfwGetCursorPos

Reads where the mouse cursor is, measured from the top-left corner of the window's content.

Signature

void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);

How it works

The position is in screen coordinates, with y growing DOWNWARDS. OpenGL's window coordinates (gl_FragCoord, glReadPixels) grow upwards, so convert with fbHeight - y after scaling to pixels.

The values are doubles: some systems report fractions of a coordinate. With the cursor disabled (glfwSetInputMode GLFW_CURSOR_DISABLED) the position is no longer limited to the window: it keeps growing as the mouse moves, which is exactly what a first-person camera needs.

Parameters

windowGLFWwindow*

The window to measure from.

xposdouble*

Where to write x, or NULL.

yposdouble*

Where to write y (down is positive), or NULL.

Tips & pitfalls

  • On high-DPI screens multiply by framebuffer size Ă· window size before using it as a pixel position.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GLFW_NOT_INITIALIZED
Called before glfwInit or after glfwTerminate.
GLFW_PLATFORM_ERROR
The operating system or window system reported a failure; the description says which.

Example

example.cpp
1double mx, my;
2glfwGetCursorPos(window, &mx, &my);
3int ww, wh, fw, fh;
4glfwGetWindowSize(window, &ww, &wh);
5glfwGetFramebufferSize(window, &fw, &fh);
6int px = (int)(mx * fw / ww);
7int py = fh - 1 - (int)(my * fh / wh);   // flip to OpenGL's bottom-up rows
8glReadPixels(px, py, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
Official GLFW documentation