import { v3_length } from "./v3_length.js";

/**
 *
 * Perform rotation on a direction vector using a 4x4 affine transform matrix.
 * Input is expected to be normalized.
 * Correctly handles non-uniform scaling.
 * Output is normalized.
 *
 * @param {number[]|Float32Array} output
 * @param {number} output_offset
 * @param {number} x
 * @param {number} y
 * @param {number} z
 * @param {number[]|Float32Array} m4
 */
export function v3_matrix4_rotate(
    output, output_offset,
    x, y, z,
    m4
) {

    const _x = m4[0] * x + m4[4] * y + m4[8] * z;
    const _y = m4[1] * x + m4[5] * y + m4[9] * z;
    const _z = m4[2] * x + m4[6] * y + m4[10] * z;

    // perform normalization
    const length = v3_length(_x, _y, _z);

    if (length > 1e-7) {

        // re-normalize
        const norm = 1 / length;

        output[output_offset] = _x * norm;
        output[output_offset + 1] = _y * norm;
        output[output_offset + 2] = _z * norm;

    } else {

        // The transform is invalid.
        // Provide arbitrary vector.

        output[output_offset] = 0;
        output[output_offset + 1] = 0;
        output[output_offset + 2] = 0;

    }
}


