/***********************************************/
/*           Copyright (c) 2025 Belmu          */
/*             All Rights Reserved             */
/***********************************************/

//////////////////////////////////////////////////////////
/*----------------- MATRIX OPERATIONS ------------------*/
//////////////////////////////////////////////////////////

vec2 diagonal2(mat4 mat) { return vec2(mat[0].x, mat[1].y); 		  }
vec3 diagonal3(mat4 mat) { return vec3(mat[0].x, mat[1].y, mat[2].z); }

vec3 projectOrthogonal(mat4 mat, vec3 v) { return diagonal3(mat) * v + mat[3].xyz; }
vec3 transform        (mat4 mat, vec3 v) { return mat3(mat)      * v + mat[3].xyz; }

//////////////////////////////////////////////////////////
/*----------------- SPACE CONVERSIONS ------------------*/
//////////////////////////////////////////////////////////

vec3 screenToView(vec3 screenPosition) {
    screenPosition = screenPosition * 2.0 - 1.0;
    return projectOrthogonal(gbufferProjectionInverse, screenPosition) / (gbufferProjectionInverse[2].w * screenPosition.z + gbufferProjectionInverse[3].w);
}

vec3 viewToWorld(vec3 viewPosition) {
    return transform(gbufferModelViewInverse, viewPosition) + cameraPosition;
}

mat3 getGeometryTBNMatrix(vec3 normal) {
    vec3 tangent = normalize(cross(normal, normalize(abs(normal.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0))));
    return mat3(tangent, cross(normal, tangent), normal);
}
