Is there a way to cast from CATransform3D to GLKMatrix4, or do I always need to manually convert them from value to value? I guess casting would be faster.
Asked
Active
Viewed 1,802 times
2 Answers
10
Unfortunately there is not as of now. There's most likely a hidden API call that Apple uses to convert via CALayers and OpenGL, but for now the following is your best bet. I would just make a utility class that would contain this in it.
- (GLKMatrix4)matrixFrom3DTransformation:(CATransform3D)transform
{
GLKMatrix4 matrix = GLKMatrix4Make(transform.m11, transform.m12, transform.m13, transform.m14,
transform.m21, transform.m22, transform.m23, transform.m24,
transform.m31, transform.m32, transform.m33, transform.m34,
transform.m41, transform.m42, transform.m43, transform.m44);
return matrix;
}
Using something like
CALayer *layer = [CALayer layer];
CATransform3D transform = layer.transform;
GLKMatrix4 matrix4 = *(GLKMatrix4 *)&transform;
Is called type punning. Unless you understand how this works, you should not use it. You cannot type pun a CATransform3D to a GLKMatrix4 as their data structures are different in memory.
reference link: type punning
GLKMatrix4
union _GLKMatrix4
{
struct
{
float m00, m01, m02, m03;
float m10, m11, m12, m13;
float m20, m21, m22, m23;
float m30, m31, m32, m33;
};
float m[16];
}
typedef union _GLKMatrix4 GLKMatrix4;
CATransform3D
struct CATransform3D
{
CGFloat m11, m12, m13, m14;
CGFloat m21, m22, m23, m24;
CGFloat m31, m32, m33, m34;
CGFloat m41, m42, m43, m44;
};
typedef struct CATransform3D CATransform3D;

TheCodingArt
- 3,436
- 4
- 30
- 53
-2
Something like this should work:
CATransform3D t;
GLKMatrix4 t2 = *((GLKMatrix4 *)&t);
t = *((CATransform3D *)&t2);
Assuming CATransform3d
and GLKMatrix4
have the same column/row setup. (I think so)
-
5Actually this will not work. I tried it out and, though it compiles there is a basic problem. CATransform3d is a matrix of CFFloat types, which are double, and GLKMatrix4 is a matrix of GLfloat, which is float. No cast will fix the size incompatibility. – Matt Mar 27 '13 at 22:39
-
Please do not promote this thought process. The two structures are completely different in memory. You may test this theory and perform a GLKMatrix3MultiplyVector3 or such (or even print out the retrieved values) and you'll instantly find that they are not handled the same in memory and will provide you with radically different results. – TheCodingArt May 05 '14 at 17:53