如何计算矩形适合屏幕所需的比例
How to calculate the required scale of a rectangle to fit the screen
我想根据相机位置使我的矩形适合屏幕尺寸。
这是矩形的 VBO 数据。
width = 50.0f;
height = 50.0f;
verticesRect = {
// Positions // Normal Coords // Texture Coords
width, height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 0.0f, // Top Right
width, -height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 1.0f, // Bottom Right
-width, -height, 0.0f, 0.0 , 0.0, 1.0 , 0.0f, 1.0f, // Bottom Left
-width, height, 0.0f, 0.0 , 0.0, 1.0 , 0.0f, 0.0f // Top Left
};
投影矩阵。
float angle = 45.0f;
glm::mat4 projection = glm::perspective(glm::radians(angle), (float)1920.0 / (float)1080.0, 0.1, 1000.0);
视图矩阵
glm::vec3 Position( 0.0 , 0.0 , 500.0);
glm::vec3 Front( 0.0 , 0.0 , 0.0);
glm::vec3 Up( 0.0 , 1.0 , 0.0);
glm::mat4 view = glm::lookAt(Position, Front , Up);
矩形对象的矩阵是
glm::model = PositionMarix * RotationMatrix * ScalingMatrix;
如何计算对象的缩放比例,使其适合屏幕大小
矩形对象可以在 z 位置平移,因此相机也可以在 z 位置移动。
在透视投影中,视口上的投影大小取决于到相机的距离 (depth
)。
aspect = width / height
height_vp = depth * 2 * atan(fov_y / 2)
width_vp = height_vp * aspect
在你的例子中,对象是围绕 (0, 0, 0) 绘制的,相机到原点的距离是 500。视野 (fov_y
) 是 glm::radians(angle)
。
使用上面的公式,您可以在视口上精确投影左下角 (-1, -1) 和右上角 (1, 1) 的矩形。由于矩形的左下角是 (-50, -50) 而右上角是 (50, 50) 你必须除以这个比例。
因此比例为:
float scale_x = 500.0f * 2.0f * atan(glm::radians(angle) / 2.0f);
float scale_y = scale_x * 1920.0f / 1080.0f;
glm::mat4 ScalingMatrix = glm::scale(glm::mat4(1.0f),
glm::vec3(scale_x / 50.0f, scale_y / 50.0f, 1.0f));
我想根据相机位置使我的矩形适合屏幕尺寸。
这是矩形的 VBO 数据。
width = 50.0f;
height = 50.0f;
verticesRect = {
// Positions // Normal Coords // Texture Coords
width, height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 0.0f, // Top Right
width, -height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 1.0f, // Bottom Right
-width, -height, 0.0f, 0.0 , 0.0, 1.0 , 0.0f, 1.0f, // Bottom Left
-width, height, 0.0f, 0.0 , 0.0, 1.0 , 0.0f, 0.0f // Top Left
};
投影矩阵。
float angle = 45.0f;
glm::mat4 projection = glm::perspective(glm::radians(angle), (float)1920.0 / (float)1080.0, 0.1, 1000.0);
视图矩阵
glm::vec3 Position( 0.0 , 0.0 , 500.0);
glm::vec3 Front( 0.0 , 0.0 , 0.0);
glm::vec3 Up( 0.0 , 1.0 , 0.0);
glm::mat4 view = glm::lookAt(Position, Front , Up);
矩形对象的矩阵是
glm::model = PositionMarix * RotationMatrix * ScalingMatrix;
如何计算对象的缩放比例,使其适合屏幕大小
矩形对象可以在 z 位置平移,因此相机也可以在 z 位置移动。
在透视投影中,视口上的投影大小取决于到相机的距离 (depth
)。
aspect = width / height
height_vp = depth * 2 * atan(fov_y / 2)
width_vp = height_vp * aspect
在你的例子中,对象是围绕 (0, 0, 0) 绘制的,相机到原点的距离是 500。视野 (fov_y
) 是 glm::radians(angle)
。
使用上面的公式,您可以在视口上精确投影左下角 (-1, -1) 和右上角 (1, 1) 的矩形。由于矩形的左下角是 (-50, -50) 而右上角是 (50, 50) 你必须除以这个比例。
因此比例为:
float scale_x = 500.0f * 2.0f * atan(glm::radians(angle) / 2.0f);
float scale_y = scale_x * 1920.0f / 1080.0f;
glm::mat4 ScalingMatrix = glm::scale(glm::mat4(1.0f),
glm::vec3(scale_x / 50.0f, scale_y / 50.0f, 1.0f));