import { clamp01 } from "../../../math/clamp01.js";
import { v3_morton_encode_normalized } from "./v3_morton_encode_normalized.js";

/**
 * Assumes that coordinates will be mapped to -1..1 range after transform
 * @param {number} x
 * @param {number} y
 * @param {number} z
 * @param {number[]} matrix matrix to transform supplied coordinates to Normalized Device Coordinates
 * @returns {number}
 */
export function v3_morton_encode_transformed(x, y, z, matrix) {

    // apply matrix transform
    const _x = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];
    const _y = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];
    const _z = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];
    const _w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];

    const d = 0.5 / _w;

    const n_x = clamp01(_x * d + 0.5);
    const n_y = clamp01(_y * d + 0.5);
    const n_z = clamp01(_z * d + 0.5);

    return v3_morton_encode_normalized(
        n_x,
        n_y,
        n_z
    );
}

