原理介绍:https://learnopengl-cn.github.io/01%20Getting%20started/08%20Coordinate%20Systems/
代码实现
为了获取模型中的顶点在窗口中显示的坐标。我们可以借用glm库对模型坐标进行转换。代码如下:
struct GLW_POINT{
double x = 0.0;
double y = 0.0;
double z = 0.0;
void clear()
{
x = 0.0;
y = 0.0;
z = 0.0;
}
GLW_POINT(){
clear();
}
};
GLW_POINT modelPosTo2D(const GLW_POINT &point)
{
GLW_POINT p;
glm::mat4 mat4Model;
glm::mat4 mat4Projection;
glm::mat4 mat4View;
mat4Model = glm::mat4(1.0);
mat4Projection = glm::perspective(glm::radians(45),
w / h, 0.1f, 100.0f);
mat4View = glm::mat4(1.0);
glm::vec4 pos = glm::vec4(point.x,point.y,point.z,1.0);
glm::vec4 res = mat4Projection * mat4View * mat4Model * pos;
float w = glm::value_ptr(res)[3];
if(w != 0){
p.x = glm::value_ptr(res)[0] / w;
p.y = glm::value_ptr(res)[1] / w;
p.z = glm::value_ptr(res)[2] / w;
}
return p;
}
其中w与h是显示区域的大小,mat4View为观察矩阵。