OpenGL加载纹理及分屏滤镜实现

·  阅读 188

一、纹理加载流程

绘制流程图

OpenGL 的 API 设计上,一般都是将创建的纹理或者缓冲区 id,绑定到对应的 Target 上。后续调用都是用 Target 获取当前绑定的 纹理或者缓冲区,进行读写。

这也要求为了安全,每次都要调用一下绑定,然后在读写对应的内容。

现在面向对象的语言一般习惯创建一个 纹理或者缓冲区对象,将参数设置到这个对象上。最终将这个对象传递给 内部使用。

但是这种设计就需要这个对象满足接口规范,一定程度上提高了 API 复杂度,限制了各种语言的发挥。

OpenGL 只能拿到一个 id,所有操作都是接口调用,对外不透明,给了各种语言极大的自由度。

完整代码

Normal.vsh

attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordVarying;

void main(void) {
    gl_Position = Position;
    TextureCoordVarying = TextureCoords;
}
复制代码

Normal.fsh

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec4 mask = texture2D(Texture, TextureCoordVarying);
    gl_FragColor = vec4(mask.rgb, 1.0);
}
复制代码
#import "DocViewController.h"
#import <GLKit/GLKit.h>

typedef struct {
    GLKVector3 positionCoord;
    GLKVector2 textureCoord;
} SenceVertex;

@interface DocViewController ()

@property (nonatomic, assign) SenceVertex *vertices;
@property (nonatomic, strong) EAGLContext *context;
// 着色器程序
@property (nonatomic, assign) GLuint program;
// 顶点缓存
@property (nonatomic, assign) GLuint vertexBuffer;
// 纹理 ID
@property (nonatomic, assign) GLuint textureID;

@end

@implementation DocViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //设置背景颜色
    self.view.backgroundColor = [UIColor blackColor];
    // 滤镜处理初始化
    [self filterInit];
    // 绘制
    [self RenderLayer];
}

- (void)filterInit {
    // 1.上下文
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    [EAGLContext setCurrentContext:self.context];

    // 2.顶点数组
    self.vertices = malloc(sizeof(SenceVertex) * 4);

    //3.初始化顶点(0,1,2,3)的顶点坐标以及纹理坐标
    self.vertices[0] = (SenceVertex){{-1, 1, 0}, {0, 1}};
    self.vertices[1] = (SenceVertex){{-1, -1, 0}, {0, 0}};
    self.vertices[2] = (SenceVertex){{1, 1, 0}, {1, 1}};
    self.vertices[3] = (SenceVertex){{1, -1, 0}, {1, 0}};

    // 4.创建图层
    CAEAGLLayer *layer = [[CAEAGLLayer alloc] init];
    layer.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width);
    layer.contentsScale = [UIScreen mainScreen].scale;
    [self.view.layer addSublayer:layer];

    // 5.绑定渲染缓冲区
    [self bindRenderLayer:layer];

    // 6.解压缩图片
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"timg" ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    self.textureID = [self createTextureWithImage:image];

    // 7.视口
    glViewport(0, 0, [self drawableWidth], [self drawableHeight]);

    // 8.顶点
    GLuint vertexBuffer;
    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(SenceVertex) * 4, self.vertices, GL_STATIC_DRAW);

    // 9.设置默认着色器
    [self setupNormalShaderProgram];

    // 10.将顶点缓存保存
    self.vertexBuffer = vertexBuffer;
}

- (void)bindRenderLayer:(CAEAGLLayer *)layer {
    // 1.初始化渲染缓冲区
    GLuint renderBuffer, frameBuffer;

    // 2.获取、绑定渲染缓冲区,将渲染缓冲区与layer建立连接
    glGenRenderbuffers(1, &renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
    [self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer];

    // 3.获取、绑定帧缓冲区,将渲染缓冲区附着到帧缓冲区
    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBuffer);
}

- (GLuint)createTextureWithImage:(UIImage *)image {
    CGImageRef cgImageRef = image.CGImage;
    if (!cgImageRef) {
        NSLog(@"load image failure");
        exit(1);
    }

    //TODO: 图片太大绘制出来是黑屏
    GLuint width = (GLuint)CGImageGetWidth(cgImageRef) / 10;
    GLuint height = (GLuint)CGImageGetHeight(cgImageRef) / 10;
    CGRect rect = CGRectMake(0, 0, width, height);
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    void *imageData = malloc(width * height * 4);
    CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8, width * 4, space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    // 翻转
    CGContextTranslateCTM(context, 0, height);
    CGContextScaleCTM(context, 1.0f, -1.0f);

    CGColorSpaceRelease(space);
    CGContextClearRect(context, rect);

    CGContextDrawImage(context, rect, cgImageRef);

    GLuint textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);


    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // textureID 默认在 0 层
    glBindTexture(GL_TEXTURE_2D, 0);

    CGContextRelease(context);
    free(imageData);

    return textureID;
}

/// 选择默认着色器,无特效
- (void)setupNormalShaderProgram {
    [self setupShaderProgramWithName:@"Normal"];
}

- (void)setupShaderProgramWithName:(NSString *)name {
    GLuint program = [self programWithShaderName:name];
    glUseProgram(program);

    GLuint positionSlot = glGetAttribLocation(program, "Position");
    GLuint textureSlot = glGetUniformLocation(program, "Texture");
    GLuint TextureCoordSlot = glGetAttribLocation(program, "TextureCoords");

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, self.textureID);

    glUniform1i(textureSlot, 0);

    glEnableVertexAttribArray(positionSlot);
    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, positionCoord));

    glEnableVertexAttribArray(TextureCoordSlot);
    glVertexAttribPointer(TextureCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(SenceVertex), NULL + offsetof(SenceVertex, textureCoord));

    self.program = program;
}

#pragma mark -shader compile and link
//link Program
- (GLuint)programWithShaderName:(NSString *)shaderName {
    //1. 编译顶点着色器/片元着色器
    GLuint vertexShader = [self compileShaderWithName:shaderName type:GL_VERTEX_SHADER];
    GLuint fragmentShader = [self compileShaderWithName:shaderName type:GL_FRAGMENT_SHADER];

    //2. 将顶点/片元附着到program
    GLuint program = glCreateProgram();
    glAttachShader(program, vertexShader);
    glAttachShader(program, fragmentShader);

    //3.linkProgram
    glLinkProgram(program);

    //4.检查是否link成功
    GLint linkSuccess;
    glGetProgramiv(program, GL_LINK_STATUS, &linkSuccess);
    if (linkSuccess == GL_FALSE) {
        GLchar messages[256];
        glGetProgramInfoLog(program, sizeof(messages), 0, &messages[0]);
        NSString *messageString = [NSString stringWithUTF8String:messages];
        NSAssert(NO, @"program链接失败:%@", messageString);
        exit(1);
    }
    //5.返回program
    return program;
}

//编译shader代码
- (GLuint)compileShaderWithName:(NSString *)name type:(GLenum)shaderType {

    //1.获取shader 路径
    NSString *shaderPath = [[NSBundle mainBundle] pathForResource:name ofType:shaderType == GL_VERTEX_SHADER ? @"vsh" : @"fsh"];
    NSError *error;
    NSString *shaderString = [NSString stringWithContentsOfFile:shaderPath encoding:NSUTF8StringEncoding error:&error];
    if (!shaderString) {
        NSAssert(NO, @"读取shader失败");
        exit(1);
    }

    //2. 创建shader->根据shaderType
    GLuint shader = glCreateShader(shaderType);

    //3.获取shader source
    const char *shaderStringUTF8 = [shaderString UTF8String];
    int shaderStringLength = (int)[shaderString length];
    glShaderSource(shader, 1, &shaderStringUTF8, &shaderStringLength);

    //4.编译shader
    glCompileShader(shader);

    //5.查看编译是否成功
    GLint compileSuccess;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &compileSuccess);
    if (compileSuccess == GL_FALSE) {
        GLchar messages[256];
        glGetShaderInfoLog(shader, sizeof(messages), 0, &messages[0]);
        NSString *messageString = [NSString stringWithUTF8String:messages];
        NSAssert(NO, @"shader编译失败:%@", messageString);
        exit(1);
    }
    //6.返回shader
    return shader;
}

- (void)RenderLayer {
    // 重新绘制
    glUseProgram(self.program);
    glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer);

    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(1, 1, 1, 1);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    [self.context presentRenderbuffer:GL_RENDERBUFFER];
}

//获取渲染缓存区的宽
- (GLint)drawableWidth {
    GLint backingWidth;
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
    return backingWidth;
}

//获取渲染缓存区的高
- (GLint)drawableHeight {
    GLint backingHeight;
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
    return backingHeight;
}

@end
复制代码

二、分屏滤镜着色器文件

以下为分屏滤镜着色器文件,顶点着色器文件相同,以下只展示片元着色器文件

二分滤镜着色器

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec2 uv = TextureCoordVarying.xy;
    float y;
    if (uv.y >= 0.0 && uv.y <= 0.5) {
        y = uv.y + 0.25;
    } else {
        y = uv.y - 0.25;
    }
    gl_FragColor = texture2D(Texture, vec2(uv.x, y));
}

复制代码

三分滤镜着色器

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec2 uv = TextureCoordVarying.xy;
    float y;
    if (uv.y < 1.0 / 3.0) {
        y = uv.y + 1.0 / 3.0;
    } else if (uv.y > 2.0 / 3.0) {
        y = uv.y - 1.0 / 3.0;
    } else {
        y = uv.y;
    }
    gl_FragColor = texture2D(Texture, vec2(uv.x, y));
}

复制代码

四分滤镜着色器

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec2 uv = TextureCoordVarying.xy;
    float x;
    float y;
    if (uv.x < 0.5) {
        x = uv.x * 2.0;
    } else {
        x = (uv.x - 0.5) * 2.0;
    }
    if (uv.y < 0.5) {
        y = uv.y * 2.0;
    } else {
        y = (uv.y - 0.5) * 2.0;
    }
    gl_FragColor = texture2D(Texture, vec2(x, y));
}
复制代码

六分滤镜着色器

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec2 uv = TextureCoordVarying.xy;
    float x;
    float y;
    // 三行两列
//    if (uv.x < 0.5) {
//        x = uv.x + 1.0 / 6.0;
//    } else {
//        x = uv.x - 1.0 / 6.0;
//    }
//    if (uv.y < 1.0 / 3.0) {
//        y = uv.y + 1.0 / 3.0;
//    } else if (uv.y > 2.0 / 3.0) {
//        y = uv.y - 1.0 / 3.0;
//    } else {
//        y = uv.y;
//    }
    // 两行三列
    if (uv.x < 1.0 / 3.0) {
        x = uv.x + 1.0 / 3.0;
    } else if (uv.x > 2.0 / 3.0) {
        x = uv.x - 1.0 / 3.0;
    } else {
        x = uv.x;
    }
    if (uv.y < 0.5) {
        y = uv.y + 1.0 / 6.0;
    } else {
        y = uv.y - 1.0 / 6.0;
    }
    gl_FragColor = texture2D(Texture, vec2(x, y));
}

复制代码

九分滤镜着色器

precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordVarying;

void main(void) {
    vec2 uv = TextureCoordVarying.xy;
    float x;
    float y;
    // load middle
//    if (uv.x < 1.0 / 3.0) {
//        x = uv.x + 1.0 / 3.0;
//    } else if (uv.x > 2.0 / 3.0) {
//        x = uv.x - 1.0 / 3.0;
//    } else {
//        x = uv.x;
//    }
//    if (uv.y < 1.0 / 3.0) {
//        y = uv.y + 1.0 / 3.0;
//    } else if (uv.y > 2.0 / 3.0) {
//        y = uv.y - 1.0 / 3.0;
//    } else {
//        y = uv.y;
//    }
    
    // load all
    if (uv.x < 1.0 / 3.0) {
        x = uv.x * 3.0;
    } else if (uv.x < 2.0 / 3.0) {
        x = (uv.x - 1.0 / 3.0) * 3.0;
    } else {
        x = (uv.x - 2.0 / 3.0) * 3.0;
    }
    if (uv.y < 1.0 / 3.0) {
        y = uv.y * 3.0;
    } else if (uv.y < 2.0 / 3.0) {
        y = (uv.y - 1.0 / 3.0) * 3.0;
    } else {
        y = (uv.y - 2.0 / 3.0) * 3.0;
    }
    gl_FragColor = texture2D(Texture, vec2(x, y));
}

复制代码
分类:
阅读
标签:
分类:
阅读
标签:
收藏成功!
已添加到「」, 点击更改