Menu
Sites
Language

set lookat matrix in OpenGL ES 2.0

OpenGL ES 2.0 deprecate the GLU tools, we have following codes to replace the functionality of the tool gluLookAt().
void translate_xyz(float* result, const float translatex,
		const float translatey, const float translatez) {
	result[12] += result[0] * translatex + result[4] * translatey
			+ result[8] * translatez;
	result[13] += result[1] * translatex + result[5] * translatey
			+ result[9] * translatez;
	result[14] += result[2] * translatex + result[6] * translatey
			+ result[10] * translatez;
	result[15] += result[3] * translatex + result[7] * translatey
			+ result[11] * translatez;
}

float length(const float x, const float y, const float z) {
	return (float) sqrt(x*x + y*y +z*z);
}

void view_set_lookat(float* result,
		const float eyex, const float eyey, const float eyez,
		const float centerx, const float centery, const float centerz,
		const float upx, const float upy, const float upz) {

	float fx = centerx - eyex;
	float fy = centery - eyey;
	float fz = centerz - eyez;

	// normalize f
	float rlf = 1.0f / length(fx, fy, fz);
	fx *= rlf;
	fy *= rlf;
	fz *= rlf;

	// compute s = f x up (x means "cross product")
    float sx = fy * upz - fz * upy;
    float sy = fz * upx - fx * upz;
    float sz = fx * upy - fy * upx;

    // and normalize s
    float rls = 1.0f / length(sx, sy, sz);
    sx *= rls;
    sy *= rls;
    sz *= rls;

    //The up vector must not be parallel to the line of sight from the eye point to the reference point.
    if((0 == sx)&&(0 == sy)&&(0 == sz))
    	return;
    	
    // compute u = s x f
    float ux = sy * fz - sz * fy;
    float uy = sz * fx - sx * fz;
    float uz = sx * fy - sy * fx;

    result[0] = sx;
    result[1] = ux;
    result[2] = -fx;
    result[3] = 0.0f;

    result[4] = sy;
    result[5] = uy;
    result[6] = -fy;
    result[7] = 0.0f;

    result[8] = sz;
    result[9] = uz;
    result[10] = -fz;
    result[11] = 0.0f;

    result[12] = 0.0f;
    result[13] = 0.0f;
    result[14] = 0.0f;
    result[15] = 1.0f;

    translate_xyz(result, -eyex, -eyey, -eyez);
}

Responses

1 Replies
Jean Yang

Added following judgement to make sure the up vector not parallel to forward line.

    //The UP vector must not be parallel to the line of sight from the eye point to the reference point.
    if((0 == sx)&&(0 == sy)&&(0 == sz))
     return;