import {
    sky_hosek_compute_irradiance_by_direction,
    sky_hosek_precompute
} from "../sky/hosek/sky_hosek_compute_irradiance_by_direction.js";
import { vec3 } from "gl-matrix";
import { array_copy } from "../../../../core/collection/array/array_copy.js";
import { max2 } from "../../../../core/math/max2.js";

export function make_sky_hosek(sun = [0, 1, 0], turbidity = 1, overcast = 0, albedo = [0, 0, 0]) {
    const coeffs = new Float32Array(27);
    const rad = new Float32Array([1, 1, 1]);
    const sun_position = new Float32Array([sun[0], sun[2], sun[1]]);

    vec3.normalize(sun_position, sun_position);

    sky_hosek_precompute(coeffs, rad, sun_position, turbidity, albedo, overcast);

    const v3 = [];

    const value_scale = 8e-5;

    return (result, result_offset, direction, direction_offset) => {
        const d_x = direction[direction_offset];
        const d_z = direction[direction_offset + 2];
        const d_y = direction[direction_offset + 1];

        sky_hosek_compute_irradiance_by_direction(
            v3, coeffs, rad, sun_position,
            d_z ,
            d_x ,
            d_y ,
        );

        vec3.scale(v3, v3, value_scale);

        // clamp sky contribution
        v3[0] = max2(0, v3[0]);
        v3[1] = max2(0, v3[1]);
        v3[2] = max2(0, v3[2]);


        array_copy(v3, 0, result, result_offset, 3);
    }
}
