import { insert_after } from "../../../../../../core/primitives/strings/insert_after.js";
import PREAMBLE_COMMON from "../common.js";

import PREAMBLE from "./preable.vert.js";

//language=GLSL
const SHADER_CHUNK_ACCUMULATION = `
    {
        // lookup nearby tet
        vec3 lpv_mesh_bounds_min = lpv_v3_bounds_min;
        vec3 lpv_mesh_bounds_max = lpv_v3_bounds_max;
        vec3 lookup_coordinates = (worldPosition.xyz - lpv_mesh_bounds_min) / (lpv_mesh_bounds_max - lpv_mesh_bounds_min) ;
        
        uint nearest_tet = lpv_guess_initial_tet( worldPosition.xyz );

        uint tet;
        vec4 barycentric_coordinates;
        lpv_walk_to_tetrahedron(position, nearest_tet, tet, barycentric_coordinates);

        vec3 worldNormal = normalize(inverseTransformDirection( normalize(normal), viewMatrix ));
        vec3 view_direction = vec3(0.0); // TODO build an actual view direction vector
                
        vec4 weights = lvp_mask_weights_by_visibility(worldPosition.xyz, worldNormal, view_direction, tet, barycentric_coordinates);  
        
        if(tet == INVALID_TET){
            lpv_values = vec3[](
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0),
                
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0),
            
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0),
                vec3(0.0, 0.0, 0.0)
            );
        }else{
            
                    
            lpv_values = lpv_interpolate_probes(weights, tet);
        }
    }
`

/**
 *
 * @param {string} source
 */
export function build_vertex_shader(source) {
    let result = PREAMBLE + PREAMBLE_COMMON + source;

    result = insert_after(
        result,
        '#include <fog_vertex>',
        SHADER_CHUNK_ACCUMULATION
    );

    // console.log(result)

    return result;
}