```
void Quat::FromMatrix(const Mat3& mat)
{
float trace = mat(0, 0) + mat(1, 1) + mat(2, 2);
if (trace > nv_zero){
float scale = sqrtf(trace + nv_one);
w = nv_zero_5 * scale;
scale = nv_zero_5 / scale;
x = scale * (mat(2, 1) - mat(1, 2));
y = scale * (mat(0, 2) - mat(2, 0));
z = scale * (mat(1, 0) - mat(0, 1));
}
else
{
static int next[] = { 1, 2, 0 };
int i = 0;
if (mat(1, 1) > mat(0, 0))
i = 1;
if (mat(2, 2) > mat(i, i))
i = 2;
int j = next[i];
int k = next[j];
float scale = sqrtf(mat(i, i) - mat(j, j) - mat(k, k) + 1);
float* q[] = { &x, &y, &z };
*q[i] = 0.5f * scale;
scale = 0.5f / scale;
w = scale * (mat(k, j) - mat(j, k));
*q[j] = scale * (mat(j, i) + mat(i, j));
*q[k] = scale * (mat(k, i) + mat(i, k));
}
}
```