OpenGL 纹理翻转策略

2020-08-05  本文已影响0人  _涼城

Open GL纹理翻转

  在使用OpenGL函数加载纹理到图形时,经常遇到纹理上下颠倒的问题。原因是因为OpenGL要求纹理坐标原点(0,0)在左下角。


OpenGL纹理坐标系.png

  而图片中像素的存储顺序是从左上到右下的,因此我们需要对我们的坐标系进行一次Y轴的“翻转”,保持原点坐标一致。

翻转方案

1. 利用旋转矩阵翻转图形

顶点着色器代码,顶点坐标与旋转矩阵相乘得到最终的顶点坐标


attribute vec4 position;
attribute vec2 textCoordinate;
uniform mat4 rotateMatrix;

varying lowp vec2 varyTextCoord;

void main()
{
    varyTextCoord = textCoordinate;

    vec4 vPos = position;
    vPos = vPos * rotateMatrix;
    gl_Position = vPos;
}

外部传递旋转180度的矩阵

-(void)rotateTextureImage
{
    //注意,想要获取shader里面的变量,这里记得要在glLinkProgram后面,后面,后面!
    //1. rotate等于shaderv.vsh中的uniform属性,rotateMatrix
    GLuint rotate = glGetUniformLocation(self.myPrograme, "rotateMatrix");

    //2.获取渲旋转的弧度
    float radians = 180 * 3.14159f / 180.0f;
    //3.求得弧度对于的sin\cos值
    float s = sin(radians);
    float c = cos(radians);

    //4.因为在3D课程中用的是横向量,在OpenGL ES用的是列向量
    /*
     参考Z轴旋转矩阵
     */
    GLfloat zRotation[16] = {
        c,-s,0,0,
        s,c,0,0,
        0,0,1,0,
        0,0,0,1
    };

    //5.设置旋转矩阵
    /*
     glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
     location : 对于shader 中的ID
     count : 个数
     transpose : 转置
     value : 指针
     */
    glUniformMatrix4fv(rotate, 1, GL_FALSE, zRotation);

}
2. 解压图片时将位图翻转

平移+倒转 得到翻转的图像

 CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;

size_t width = CGImageGetWidth(spriteImage);
size_t height = CGImageGetHeight(spriteImage);
GLubyte * spriteData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));

CGContextRef spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width*4,CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);

CGRect rect = CGRectMake(0, 0, width, height);
CGContextDrawImage(spriteContext, CGRectMake(0, 0, width, height), spriteImage);
/*开始翻转*/
CGContextTranslateCTM(spriteContext, rect.origin.x, rect.origin.y);
CGContextTranslateCTM(spriteContext, 0, rect.size.height);
CGContextScaleCTM(spriteContext, 1.0, -1.0);
CGContextTranslateCTM(spriteContext, -rect.origin.x, -rect.origin.y);
 /*结束翻转*/
CGContextDrawImage(spriteContext, rect, spriteImage); 

CGContextRelease(spriteContext);
glBindTexture(GL_TEXTURE_2D, 0);

3. 修改片元着色器的纹理坐标
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main()
{
    //gl_FragColor = texture2D(colorMap, varyTextCoord);
    gl_FragColor = texture2D(colorMap, vec2(varyTextCoord.x,1.0-varyTextCoord.y));
//因为纹理坐标的范围是0-1,所以翻转的话都统一用1去减 
}


4. 修改顶点着色器纹理坐标

顶点数据的纹理坐标,翻转y值(用1减去y坐标)。

attribute vec4 position;
attribute vec2 textCoordinate;
varying lowp vec2 varyTextCoord;

void main()
{
    //varyTextCoord = textCoordinate;
    varyTextCoord = vec2(textCoordinate.x,1.0-textCoordinate.y);
    gl_Position = position;

//因为纹理坐标的范围是0-1,所以翻转的话都统一用1去减 
}

5. 直接从源纹理坐标数据修改映射关系

将纹理坐标按照翻转后映射

上一篇 下一篇

猜你喜欢

热点阅读