Skip to content

Instantly share code, notes, and snippets.

@AyadiMehdi
Forked from sakrist/GLKMathUtils
Created March 8, 2017 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AyadiMehdi/d9d525093017362845441ac03d507477 to your computer and use it in GitHub Desktop.
Save AyadiMehdi/d9d525093017362845441ac03d507477 to your computer and use it in GitHub Desktop.
GLKMathProject and GLKMathUnproject
GLKVector3 GLKMathProject(GLKVector3 object, GLKMatrix4 model, GLKMatrix4 projection, int *viewport) {
assert(viewport);
GLKVector4 v4 = GLKVector4MakeWithVector3(object, 1.0);
GLKVector4 v = GLKMatrix4MultiplyVector4(model, v4);
v = GLKMatrix4MultiplyVector4(projection, v);
v.v[3] = 1.0/v.v[3];
v.v[0] *= v.v[3];
v.v[1] *= v.v[3];
v.v[2] *= v.v[3];
float x = (v.v[0] * 0.5 + 0.5) * viewport[2] + viewport[0];
float y = (v.v[1] * 0.5 + 0.5) * viewport[3] + viewport[1];
float z = (1.0 + v.v[2])*0.5;
return GLKVector3Make(x, y, z);
}
GLKVector3 GLKMathUnproject(GLKVector3 window, GLKMatrix4 model, GLKMatrix4 projection, int *viewport, bool *success) {
assert(viewport);
bool canInvert = false;
GLKMatrix4 inverted = GLKMatrix4Invert(GLKMatrix4Multiply(projection, model), &canInvert);
if (success) {
*success = canInvert;
}
if (!canInvert) {
return GLKVector3Make(0.0f, 0.0f, 0.0f);
}
GLKVector4 normalisedVector = GLKVector4Make((2 * window.x / viewport[2] - 1),
(2 * (window.y - viewport[1]) / viewport[3] - 1),
2*window.z - 1,
1);
GLKVector4 _point = GLKMatrix4MultiplyVector4(inverted, normalisedVector);
_point.v[3] = 1.0/_point.v[3];
GLKVector3 vec = GLKVector3Make(_point.v[0]*_point.v[3], _point.v[1]*_point.v[3], _point.v[2]*_point.v[3]);
return vec;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment