OpenGL 2D模式

//
// left top 这里设置的默认是左上角
//
void push_view2d(int left, int top, int width, int height)
{
    //glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT);
    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
 
    //直角坐标系
    //glOrtho(left, width, top, height, 0, INT_MAX);
    //十字坐标系
    //glOrtho(-width/2, width/2, -height/2, height/2, 0, INT_MAX);//
 
    //windows坐标系
    //glOrtho(left, width, height, top, -1.0, 1000000.0);
    //这里的-1要去掉,不然绘制会有舍入偏差
    //glOrtho(left, left+width-1, top+height-1, top, 0, INT_MAX);
    glOrtho(left, left+width, top+height, top, 0, INT_MAX);
 
    //glOrtho(0, width-1, -height+1, 0, 0, INT_MAX);
    //glTranslatef(0, -height+1, 0);
 
    //重新设置正面,默认GL_CCW
    //glFrontFace(GL_CW);
 
    //反转屏幕
    //glScalef(1.0f, -1.0f, 1.0f);
    //glTranslatef(0.0f, -height, 0.0f);
 
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glDisable(GL_DEPTH_TEST);//关闭深度测试
    glDisable(GL_CULL_FACE); //关闭面剔除
}
 
//恢复视口映射设置
void pop_view2d()
{
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopAttrib();
}

函数使用方法:

glClear(...);//清屏

//先设置成800x600
//这是虚拟的屏幕尺寸。要真实的分辨率,就要和你的glViewport设置的尺寸一样
push_view2d(0, 0, 800, 600);
draw(...);
pop_view2d();

//再设置成1024x768模式,绘制一些东西
push_view2d(0, 0, 1024, 768);
draw(...);
pop_view2d();

swapbuffers();//反转缓存,显示

特别需要说明的是,OpenGL默认的起始左边在左下角,这样映射成Windows坐标之后,绘制出来的纹理是上下颠倒的。解决办法有两个,一个是绘制的时候交换一下v1、v2的坐标,另外就是制作纹理的时候,上下颠倒一下。

#define CGL_LOWER_LEFT 0    //左下角起始(默认)
#define CGL_UPPER_LEFT 1    //左上角起始(Windows)
#define CGL_COORDINATE CGL_LOWER_LEFT    //定义左上角起始
 
/*
struct vec4f
{
    float r, g, b, a;
};
struct vertex_type
{
    float x, y, z;
    float u, v;
    vec4f color; 
};
*/
 
void glcontext::draw_image(GLuint image, float x, float y, float width, float height,
    float u1, float v1, float u2, float v2)
{
    vertex_type vtx[] = {
        #if CGL_COORDINATE == CGL_LOWER_LEFT//左下角为原点
        vertex_type(x,         y,          0.0f, u1, v2, color),
        vertex_type(x + width, y,          0.0f, u2, v2, color),
        vertex_type(x + width, y + height, 0.0f, u2, v1, color),
        vertex_type(x        , y + height, 0.0f, u1, v1, color)
        #else//右下角为原点,OpenGL默认
        vertex_type(x,         y,          0.0f, u1, v1, color),
        vertex_type(x + width, y,          0.0f, u2, v1, color),
        vertex_type(x + width, y + height, 0.0f, u2, v2, color),
        vertex_type(x,         y + height, 0.0f, u1, v2, color)
        #endif
    };
    this->bind_texture(image);
    this->draw_arrays(GL_TRIANGLE_FAN, vtx, 0, 4);
}

猜你喜欢

转载自www.cnblogs.com/sdragonx/p/10989862.html