3

想要将 OpenGL 1.1 代码转换为 OpenGL 2.0。

我用的是Cocos2d v2.0(一个构建2D游戏的框架)

4

1 回答 1

2

首先你必须让你的着色器进入你的程序。您可以将着色器代码直接复制到下面显示的 const char * 中,也可以在运行时从文件加载着色器,这取决于您正在开发的平台,所以我不会展示如何做到这一点。

const char *vertexShader = "... Vertex Shader source ...";
const char *fragmentShader = "... Fragment Shader source ...";

为顶点着色器和片段着色器创建着色器并存储它们的 ID:

GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

在这里,您可以使用复制粘贴到 const char * 或从文件加载的数据填充刚刚创建的着色器:

glShaderSource(vertexShader, 1, &vertexShader, NULL);
glShaderSource(fragmentShader, 1, &fragmentShader, NULL);

然后你告诉程序编译你的着色器:

glCompileShader(vertexShader);
glCompileShader(fragmentShader);

创建一个着色器程序,它是 OpenGL 着色器的接口:

shaderProgram = glCreateProgram();

将着色器附加到着色器程序:

glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);

将着色器程序链接到您的程序:

glLinkProgram(shaderProgram);

告诉 OpenGL 你想使用你创建的着色器程序:

glUseProgram(shaderProgram);

顶点着色器:

attribute vec4 a_Position; // Attribute is data send with each vertex. Position 
attribute vec2 a_TexCoord; // and texture coordinates is the example here

uniform mat4 u_ModelViewProjMatrix; // This is sent from within your program

varying mediump vec2 v_TexCoord; // varying means it is passed to next shader

void main()
{
    // Multiply the model view projection matrix with the vertex position
    gl_Position = u_ModelViewProjMatrix* a_Position;
    v_TexCoord = a_TexCoord; // Send texture coordinate data to fragment shader.
}

片段着色器:

precision mediump float; // Mandatory OpenGL ES float precision

varying vec2 v_TexCoord; // Sent in from Vertex Shader

uniform sampler2D u_Texture; // The texture to use sent from within your program.

void main()
{
    // The pixel colors are set to the texture according to texture coordinates.
    gl_FragColor =  texture2D(u_Texture, v_TexCoord);
}
于 2012-04-04T07:42:26.733 回答