一. 背景分析
首先我们得有一张全景图片,这个图片是由两个摄像头拍摄合成到一张图片上的全景图片。有了图片,如何在手机上展示,我们使用的是一个球体的模型,想象一下,我们把一张图片贴在一个球面上,这个过程可以认为是我们将一个地球仪上切开,展开成一个长方体的世界地图的逆过程。然后想象我们站在这个球体的中心,通过不断转动这个球体,或者我们调整我们的视线就可以达到看到这个球体上物体全貌的目的。
二. 技术分析
- 可以和opengl结合使用的相关类。
(1). 使用GLKViewController和GLKView,优点是使用起来比较简单,缺点是可扩展性和移植性比较差。
(2). 使用CAEAGLLayer,有点是可以在layer上操作,可移植性高,灵活。
这里我是在CAEAGLLayer上来做的。 - 加载图片文件
由于图片的组成可能由RGB或者RGBA组成,而且,我们知道能够做为纹理贴图的图片在尺寸上也有要求,所以,我们这里使用ios的自带的类GLKTextureLoader来加载纹理。
三. 代码分析
-
初始化openGL
<pre>
self.contentScaleFactor = [[UIScreen mainScreen] scale];
CAEAGLLayer *eagLayer = (CAEAGLLayer *)self.layer;
eagLayer.opaque = true;
// 设置layer属性,kEAGLDrawablePropertyRetainedBacking 为No 表示不使用保留背景,告诉core animation不要保留任何以前的图像来重用
// kEAGLColorFormatRGBA8 告诉core animation 用8位来保存层内的每个像素点每个颜色值
eagLayer.drawableProperties = @{kEAGLDrawablePropertyRetainedBacking : [NSNumber numberWithBool:NO],
kEAGLDrawablePropertyColorFormat : kEAGLColorFormatRGBA8};
// 使用 openGLES2 来初始化context
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if (!_context ||
![EAGLContext setCurrentContext:_context]) {
NSLog(@"failed to setup EAGLContext");
}
// 生成帧缓存和颜色像素缓存
glGenFramebuffers(1, &_framebuffer);
glGenRenderbuffers(1, &_renderbuffer);
// 将生成帧缓存绑定到帧缓存的位置
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
// 将生成的颜色渲染缓存绑定到颜色渲染缓存
glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
// 调整颜色渲染缓存的尺寸以匹配layer的新尺寸
[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
// 获取渲染缓存的宽高
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &_backingWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &_backingHeight);
// 将颜色渲染缓存和帧缓存关联
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderbuffer);
// 检查帧缓存是否创建成功
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
NSLog(@"failed to make complete framebuffer object %x", status);
}
// 检查错误信息
GLenum glError = glGetError();
if (GL_NO_ERROR != glError) {
NSLog(@"failed to setup GL %x", glError);
}
// 加载着色器
if (![self loadShaders]) {
NSLog(@"加载着色器失败!!!");
}
</pre>
(1). 加载着色器
<pre>
BOOL result = NO;
GLuint vertShader = 0;
GLuint fragShader = 0;
// 创建一个渲染程序
_program = glCreateProgram();
// 编译顶点着色器
vertShader = compileShader(GL_VERTEX_SHADER, vertexShaderString);
// 编译一个数据为RGB的片元着色器
fragShader = compileShader(GL_FRAGMENT_SHADER, rgbFragmentShaderString);
// 将着色器添加到程序中
glAttachShader(_program, vertShader);
glAttachShader(_program, fragShader);
// 一般使用函数glBindAttribLocation来绑定每个着色器中的attribute变量的位置,然后用函数glVertexAttribPointer为每个attribute变量赋值
// glBindAttribLocation(_program, ATTRIBUTE_VERTEX, "position");
// glBindAttribLocation(_program, ATTRIBUTE_TEXCOORD, "texcoord");
self.vertexTexCoordAttributeIndex = 3;
glBindAttribLocation(_program, self.vertexTexCoordAttributeIndex, "texcoord");
// 链接着色器程序
glLinkProgram(_program);
// 检查链接的状态
GLint status;
glGetProgramiv(_program, GL_LINK_STATUS, &status);
if (status == GL_FALSE){
NSLog(@"Failed to link program %d",status);
goto exit;
}
result = validateProgram(_program);
// 生成一个渲染程序中的Uniform变量的引用
_uniformMatrix = glGetUniformLocation(_program, "modelViewProjectionMatrix");
_uniformSampler = glGetUniformLocation(_program, "s_texture");
exit:
if (vertShader)
glDeleteShader(vertShader);
if (fragShader)
glDeleteShader(fragShader);
if (result) {
NSLog(@"OK setup GL programm");
} else {
glDeleteProgram(_program);
_program = 0;
}
return result;
</pre>
使用的顶点着色器和片元着色器
<pre>
// 声明一个顶点着色器源码和两个片元着色器源码
NSString *const vertexShaderString = SHADER_STRING
(
attribute vec4 position;
attribute vec2 texcoord;
uniform mat4 modelViewProjectionMatrix;
varying vec2 v_texcoord;
void main()
{
gl_Position = modelViewProjectionMatrix * position;
v_texcoord = texcoord.xy;
}
);
NSString *const rgbFragmentShaderString = SHADER_STRING
(
varying highp vec2 v_texcoord;
uniform sampler2D s_texture;
void main()
{
gl_FragColor = texture2D(s_texture, v_texcoord);
}
);
</pre>
- 生成创建顶点数据缓存和纹理坐标缓存
<pre>
-
(void)setupBuffers {
GLfloat *vVertices = NULL;
GLfloat *vTextCoord = NULL;
GLushort *indices = NULL;
int numVertices = 0;
self.numIndices = esGenSphere(SphereSliceNum, SphereRadius, &vVertices, &vTextCoord, &indices, &numVertices);//Indices
glGenBuffers(1, &_vertexIndicesBufferID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vertexIndicesBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.numIndices*sizeof(GLushort), indices, GL_STATIC_DRAW);// Vertex
glGenBuffers(1, &_vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, numVertices3sizeof(GLfloat), vVertices, GL_STATIC_DRAW);glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*3, NULL);// Texture Coordinates
glGenBuffers(1, &_vertexTexCoordID);
glBindBuffer(GL_ARRAY_BUFFER, self.vertexTexCoordID);
glBufferData(GL_ARRAY_BUFFER, numVertices2sizeof(GLfloat), vTextCoord, GL_DYNAMIC_DRAW);glEnableVertexAttribArray(self.vertexTexCoordAttributeIndex);
glVertexAttribPointer(self.vertexTexCoordAttributeIndex, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*2, NULL);
}
</pre>
tips: 使用下面的函数生成球面上顶点坐标和纹理坐标数据
<pre>
//https://github.com/danginsburg/opengles-book-samples/blob/604a02cc84f9cc4369f7efe93d2a1d7f2cab2ba7/iPhone/Common/esUtil.h#L110
int esGenSphere(int numSlices, float radius, float **vertices,
float **texCoords, uint16_t **indices, int *numVertices_out) {
int numParallels = numSlices / 2;
int numVertices = (numParallels + 1) * (numSlices + 1);
int numIndices = numParallels * numSlices * 6;
float angleStep = (2.0f * ES_PI) / ((float) numSlices);
if (vertices != NULL) {
*vertices = malloc(sizeof(float) * 3 * numVertices);
}
if (texCoords != NULL) {
*texCoords = malloc(sizeof(float) * 2 * numVertices);
}
if (indices != NULL) {
*indices = malloc(sizeof(uint16_t) * numIndices);
}
for (int i = 0; i < numParallels + 1; i++) {
for (int j = 0; j < numSlices + 1; j++) {
int vertex = (i * (numSlices + 1) + j) * 3;
if (vertices) {
(*vertices)[vertex + 0] = radius * sinf(angleStep * (float)i) * sinf(angleStep * (float)j);
(*vertices)[vertex + 1] = radius * cosf(angleStep * (float)i);
(*vertices)[vertex + 2] = radius * sinf(angleStep * (float)i) * cosf(angleStep * (float)j);
}
if (texCoords) {
int texIndex = (i * (numSlices + 1) + j) * 2;
(*texCoords)[texIndex + 0] = (float)j / (float)numSlices;
(*texCoords)[texIndex + 1] = 1.0f - ((float)i / (float)numParallels);
}
}
}
// Generate the indices
if (indices != NULL) {
uint16_t *indexBuf = (*indices);
for (int i = 0; i < numParallels ; i++) {
for (int j = 0; j < numSlices; j++) {
*indexBuf++ = i * (numSlices + 1) + j;
*indexBuf++ = (i + 1) * (numSlices + 1) + j;
*indexBuf++ = (i + 1) * (numSlices + 1) + (j + 1);
*indexBuf++ = i * (numSlices + 1) + j;
*indexBuf++ = (i + 1) * (numSlices + 1) + (j + 1);
*indexBuf++ = i * (numSlices + 1) + (j + 1);
}
}
}
if (numVertices_out) {
*numVertices_out = numVertices;
}
return numIndices;
}
</pre>
使用GLKTextureLoader 来加载纹理
<pre>
[self.textureloader textureWithCGImage:image options:nil queue:NULL completionHandler:^(GLKTextureInfo *textureInfo, NSError *outError) {
if (outError){
NSLog(@"GL Error = %u", glGetError());
} else {
if (self.textureInfo.name) {
GLuint textureName = self.textureInfo.name;
glDeleteTextures(1, &textureName);
}
self.textureInfo = textureInfo;
}
}];
</pre>如何开始绘制。这里我使用的是CADisplayLink 这个类来实现
<pre>
// 初始化displayLink
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkCallback:)];
self.displayLink.preferredFramesPerSecond = 30;
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
</pre>-
绘制方法
<pre>
// 设置上下文
[EAGLContext setCurrentContext:_context];glBindVertexArrayOES(_vertexArrayID);
// 绑定帧缓存
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
// 设置视口坐标
glViewport(0, 0, _backingWidth, _backingHeight);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(_program);if (self.textureInfo != nil){
// 绑定纹理到缓存
glBindTexture(GL_TEXTURE_2D, self.textureInfo.name);[self update]; glDrawElements(GL_TRIANGLES, self.numIndices, GL_UNSIGNED_SHORT, 0);
// glDrawArrays(GL_TRIANGLES, 0, sphereVertices);
}
glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
[_context presentRenderbuffer:GL_RENDERBUFFER];
}
</pre>
这里我们做完上面的步骤,如果只是在顶点着色器中传入一个普通的单位矩阵,我们得到 的只是一个站在球体外面看到的球体的一部分,就好像我们站在太空上观察这个地球一样,所以我们要通过透视投影矩阵和各种变换矩阵,来达到我们上面说到的让我们的视线能够处在圆心处观察。
分析代码:
<pre>
float aspect = fabs(self.bounds.size.width / self.bounds.size.height);
// 生成透视投影矩阵
GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(self.overture), aspect, 0.1f, 400.0f);
// 将y轴翻转
projectionMatrix = GLKMatrix4Rotate(projectionMatrix, ES_PI, 1.0f, 0.0f, 0.0f);
GLKMatrix4 modelViewMatrix = GLKMatrix4Identity;
modelViewMatrix = GLKMatrix4RotateX(modelViewMatrix, 0.0f);
modelViewMatrix = GLKMatrix4RotateY(modelViewMatrix, 0.0f);
self.modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);
glUniformMatrix4fv(_uniformMatrix, 1, GL_FALSE, self.modelViewProjectionMatrix.m);
</pre>