如何将 window 坐标转换为标准化设备坐标?

How I can convert window coordinate into normalized device coordinates?

我有我的window坐标,我需要在这里画文字。

我使用这个功能:

void displayText(std::string const& text, float x, float y)
{
  int j = text.size();

  glColor3f(1, 1, 1);
  // std::cout << x << " " << y << std::endl;
  // std::cout << (x / 900) * (2.0 - 1.0) <<" " <<(y / 900) * (2.0 - 1.0) << std::endl;
    x = x / (float)900; //900 is my window size
    y = y / (float)900;
    x-=0.5f;
    y-=0.5f;//  std::cout << x << " "<<y << std::endl;
  glRasterPos2f(x, y);
  for(int i = 0; i < j; i++)
    glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, text[i]);
}

但它在错误的坐标中绘制文本,上下颠倒,知道吗?

glRasterPos2f 将通过完整的转换管道,因此它特别受以下因素影响:

  • 当前投影矩阵
  • 当前模型视图矩阵
  • 当前设置的视口

这意味着您的问题标题具有误导性,因为 window space 和 NDC 坐标在这里都不相关,但是 object space坐标.

为了绘制bitmap-based文本,最好在设置modelView时设置一些pixel-exact正交矩阵(匹配视口大小)作为投影 身份:

glMatrixMode(GL_PROJECTION);
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRasterPos2f(pixel_coords);
// draw bitmaps here

请注意,GL 使用数学约定,因此原点将位于屏幕的底部 左角。您可以在正交矩阵中翻转它,但仍会绘制位图,以便它们的局部左下边缘出现在光栅位置。

您应该知道,所有这些东西 - 绘制位图、固定函数坐标变换、内置 GL 矩阵函数等等 - 完全近十年 到现在已弃用。 OpenGL 的现代核心配置文件不再支持它,您将不得不使用 texture-based 方法进行字体渲染。使用带符号的距离场是一个很好的选择,可以在屏幕上显示漂亮的字体。