import { assert } from "../../../assert.js";
import { sign_not_zero } from "../../../math/sign_not_zero.js";
import { v3_array_normalize } from "../../vec3/v3_array_normalize.js";

/**
 *
 * @param {number[]} out_direction This is where the normalized direction vector will be written to
 * @param {number} out_offset Where to start writing in the output
 * @param {number[]} in_uv in the 0..1 range
 * @param {number} in_offset where to start reading in the input
 */
export function octahedral_uv_to_direction(
    out_direction, out_offset,
    in_uv, in_offset
) {

    assert.isNonNegativeInteger(out_offset, 'out_offset');
    assert.isNonNegativeInteger(in_offset, 'in_offset');

    let px = in_uv[in_offset + 0] * 2 - 1;
    let pz = in_uv[in_offset + 1] * 2 - 1;

    const abs_x = Math.abs(px);
    const abs_z = Math.abs(pz);
    const py = 1 - abs_x - abs_z;

    if (py < 0) {
        px = sign_not_zero(px) * (1 - abs_z);
        pz = sign_not_zero(pz) * (1 - abs_x);
    }

    out_direction[out_offset + 0] = px;
    out_direction[out_offset + 1] = py;
    out_direction[out_offset + 2] = pz;

    v3_array_normalize(out_direction, out_offset, out_direction, out_offset);

}

