在OpenGL ES中,将屏幕坐标转换为世界坐标需要经过以下步骤:
以下是一个示例代码,演示如何将屏幕坐标转换为世界坐标:
// 获取视口变换矩阵
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
// 获取模型视图矩阵和投影矩阵
GLfloat modelview[16], projection[16];
glGetFloatv(GL_MODELVIEW_MATRIX, modelview);
glGetFloatv(GL_PROJECTION_MATRIX, projection);
// 获取逆矩阵
GLfloat inverse_modelview[16], inverse_projection[16];
gluInvertMatrix(modelview, inverse_modelview);
gluInvertMatrix(projection, inverse_projection);
// 计算屏幕坐标
GLfloat screen_x = (2.0f * x) / viewport[2] - 1.0f;
GLfloat screen_y = 1.0f - (2.0f * y) / viewport[3];
// 计算裁剪坐标系的坐标
GLfloat clip_x = screen_x;
GLfloat clip_y = screen_y;
// 计算归一化设备坐标系的坐标
GLfloat ndc_x = clip_x;
GLfloat ndc_y = clip_y;
// 计算模型视图坐标系的坐标
GLfloat eye_x = ndc_x * inverse_projection[0] + ndc_y * inverse_projection[4] + inverse_projection[12];
GLfloat eye_y = ndc_x * inverse_projection[1] + ndc_y * inverse_projection[5] + inverse_projection[13];
GLfloat eye_z = ndc_x * inverse_projection[2] + ndc_y * inverse_projection[6] + inverse_projection[14];
GLfloat eye_w = ndc_x * inverse_projection[3] + ndc_y * inverse_projection[7] + inverse_projection[15];
// 计算世界坐标系的坐标
GLfloat world_x = eye_x * inverse_modelview[0] + eye_y * inverse_modelview[4] + eye_z * inverse_modelview[8] + eye_w * inverse_modelview[12];
GLfloat world_y = eye_x * inverse_modelview[1] + eye_y * inverse_modelview[5] + eye_z * inverse_modelview[9] + eye_w * inverse_modelview[13];
GLfloat world_z = eye_x * inverse_modelview[2] + eye_y * inverse_modelview[6] + eye_z * inverse_modelview[10] + eye_w * inverse_modelview[14];
GLfloat world_w = eye_x * inverse_modelview[3] + eye_y * inverse_modelview[7] + eye_z * inverse_modelview[11] + eye_w * inverse_modelview[15];
// 输出世界坐标系的坐标
std::cout << "World coordinates: ("<< world_x / world_w << ", "<< world_y / world_w << ", "<< world_z / world_w << ")"<< std::endl;
需要注意的是,这个示例代码仅适用于OpenGL ES 1.x和2.x版本,OpenGL ES 3.x版本需要使用不同的着色器语言和着色器程序来实现。
领取专属 10元无门槛券
手把手带您无忧上云