简体   繁体   中英

Model view matrix for a quad

For my graphics project I'm trying to implement a minimap. Unlike my usual objects I thought I could just specify the vertex coordinates in OpenGL's default camera coordinate system. So I have my vertices at (-1,1,0) , (1,1,0) , (-1,-1,0) and (1,-1,0) . I don't use a projection matrix for the calculation of gl_Position . If I don't use a model view matrix, the quad with those 4 vertices fills the whole screen (as expected). Now I want to scale this quad to 100x100 pixels and put it in the upper right corner of the viewport, with a distance of 40 to the border of the viewport.

I tried to setup the model view matrix like this:

// Move to upper right corner - targetDistance
translate(vec3((viewportWidth - targetDistance) / viewportWidth, (viewportHeight - targetDistance) / viewportHeight), 0.0)
// Move upper right corner to origin
* translate(vec3(-0.5*targetWidth / viewportWidth,-0.5*targetHeight / viewportWidth, 0.0)
// Scale to desired size
* scale(vec3(targetWidth / viewportWidth, targetHeight / viewportHeight, 0.0)

The corresponding CPP code looks like this (uses glm).

glm::uvec2 viewportSize = this->camera->getViewportSize();
const float targetWidth = 100;
const float targetHeight = 100;
const float targetDistance = 40;

glm::mat4 modelViewMatrix =
  glm::translate(
      glm::vec3((viewportSize.x - targetDistance) / viewportSize.x,
                (viewportSize.y - targetDistance) / viewportSize.y, 0.0)) *
  glm::translate(glm::vec3(-0.5f * targetWidth / viewportSize.x,
                           -0.5f * targetHeight / viewportSize.y, 0.0f)) *
  glm::scale(glm::vec3(targetWidth / viewportSize.x,
                       targetHeight / viewportSize.y, 0.0f));

Unfortunately, this doesn't work. The minimap gets scaled correctly and put in the upper right corner but there is no distance to the border (or even a negative one).

Instead of fiddling with the vertex coordinate transformation I suggest something far more simpler? Just move the viewport itself into the desired corner and size of the window:

glViewport(
    lower_left_corner_in_the_window_in_pixels,
    lower_right_corner_in_the_window_in_pixels,
    width_in_pixels,
    height_in_pixels )

if your initial though on this "how should I do this? I set viewport in the resize (reshape) function" then you're doing it wrong. All calls to glViewport belong into the drawing process, ie should be placed in the drawing code, right before the OpenGL calls that depend on the viewport being set are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM