glViewport
Sets which rectangle of the window the rendered image is mapped to.
Signature
void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
How it works
After the vertex shader, positions are in normalized device coordinates (NDC), from -1 to 1 on each axis. The viewport is the final step that turns them into pixel coordinates: -1 becomes x, +1 becomes x + width.
You usually set it once to the full framebuffer size, and again every time the window is resized.
Parameters
Left edge in pixels, from the LEFT of the window.
Bottom edge in pixels, from the BOTTOM of the window (OpenGL's origin is bottom-left).
Width in pixels.
Height in pixels.
Tips & pitfalls
On high-DPI screens the framebuffer is bigger than the window: use glfwGetFramebufferSize, not the window size.
When rendering into a framebuffer object of a different size (e.g. a shadow map), set the viewport to that size and restore it afterwards.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GL_INVALID_VALUE
- width or height is negative.
Example
1void framebufferSizeCallback(GLFWwindow*, int w, int h) {
2 glViewport(0, 0, w, h);
3}
4glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);