×

学习OpenGL ES之基本光照

获取示例代码

``````attribute vec4 position;
attribute vec3 normal;

uniform float elapsedTime;
uniform mat4 projectionMatrix;
uniform mat4 cameraMatrix;
uniform mat4 modelMatrix;

varying vec3 fragNormal;

void main(void) {
mat4 mvp = projectionMatrix * cameraMatrix * modelMatrix;
fragNormal = normal;
gl_Position = mvp * position;
}
``````

``````precision highp float;

varying vec3 fragNormal;

uniform float elapsedTime;
uniform vec3 lightDirection;
uniform mat4 normalMatrix;

void main(void) {
vec3 normalizedLightDirection = normalize(-lightDirection);
vec3 transformedNormal = normalize((normalMatrix * vec4(fragNormal, 1.0)).xyz);

float diffuseStrength = dot(normalizedLightDirection, transformedNormal);
diffuseStrength = clamp(diffuseStrength, 0.0, 1.0);
vec3 diffuse = vec3(diffuseStrength);

vec3 ambient = vec3(0.3);

vec4 finalLightStrength = vec4(ambient + diffuse, 1.0);
vec4 materialColor = vec4(1.0, 0.0, 0.0, 1.0);

gl_FragColor = finalLightStrength * materialColor;
}
``````

``````vec3 normalizedLightDirection = normalize(-lightDirection);
``````

``````- (void)bindAttribs:(GLfloat *)triangleData {
// attribute vec4 position;
// attribute vec4 color;
glEnableVertexAttribArray(positionAttribLocation);
glEnableVertexAttribArray(colorAttribLocation);

// glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr)
// indx: 上面Get到的Location
// size: 有几个类型为type的数据，比如位置有x,y,z三个GLfloat元素，值就为3
// type: 一般就是数组里元素数据的类型
// normalized: 暂时用不上
// stride: 每一个点包含几个byte，本例中就是6个GLfloat，x,y,z,r,g,b
// ptr: 数据开始的指针，位置就是从头开始，颜色则跳过3个GLFloat的大小
glVertexAttribPointer(positionAttribLocation, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (char *)triangleData);
glVertexAttribPointer(colorAttribLocation, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (char *)triangleData + 3 * sizeof(GLfloat));
}
``````

``````- (void)drawXPlanes {
static GLfloat triangleData[] = {
// X轴0.5处的平面
0.5,  -0.5,    0.5f, 1,  0,  0,
0.5,  -0.5f,  -0.5f, 1,  0,  0,
0.5,  0.5f,   -0.5f, 1,  0,  0,
0.5,  0.5,    -0.5f, 1,  0,  0,
0.5,  0.5f,    0.5f, 1,  0,  0,
0.5,  -0.5f,   0.5f, 1,  0,  0,
// X轴-0.5处的平面
-0.5,  -0.5,    0.5f, -1,  0,  0,
-0.5,  -0.5f,  -0.5f, -1,  0,  0,
-0.5,  0.5f,   -0.5f, -1,  0,  0,
-0.5,  0.5,    -0.5f, -1,  0,  0,
-0.5,  0.5f,    0.5f, -1,  0,  0,
-0.5,  -0.5f,   0.5f, -1,  0,  0,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 12);
}
``````

``````@property (assign, nonatomic) GLKVector3 lightDirection; // 平行光光照方向
``````

``````// 设置平行光方向
self.lightDirection = GLKVector3Make(0, -1, 0);
``````

``````bool canInvert;
GLKMatrix4 normalMatrix = GLKMatrix4InvertAndTranspose(self.modelMatrix, &canInvert);
if (canInvert) {
glUniformMatrix4fv(modelMatrixUniformLocation, 1, 0, normalMatrix.m);
}

glUniform3fv(lightDirectionUniformLocation, 1,self.lightDirection.v);
``````

OpenGL ES