
#import bevy_sprite::{mesh2d_vertex_output::VertexOutput,
mesh2d_functions::{get_model_matrix, mesh2d_position_local_to_clip}}

@group(1) @binding(0) var<storage, read> points: array<vec2<f32>>;
@group(1) @binding(1) var<uniform> width: f32;
@group(1) @binding(2) var base_color_texture: texture_2d<f32>;
@group(1) @binding(3) var base_color_sampler: sampler;

struct Vertex {
    @builtin(vertex_index) index: u32,
    @location(0) position: vec3<f32>,
    @location(1) normal: vec2<f32>,
    @location(2) uv: vec2<f32>,
};

@vertex
fn vertex(vertex: Vertex) -> VertexOutput {
    var out: VertexOutput;
    var i: u32 = vertex.index/2u;
    var tangent = normalize(points[i - 1u] - 2.0*vertex.position.xy - points[i + 1u]);
    var normal = vec2<f32>(tangent.y, -tangent.x);
    var sign = 2.0*f32(vertex.index == i*2u) - 1.0;

    out.position = mesh2d_position_local_to_clip(
        get_model_matrix(0u),
        vec4<f32>(points[i] - normal*sign*width, 0.0, 1.0)
    );
    
    out.uv = vertex.uv;
    return out;
}

@fragment
fn fragment(mesh: VertexOutput) -> @location(0) vec4<f32> {
    //return floor(vec4<f32>(mesh.uv, 0.0, 1.0)*20.0)/20.0;
    var l = f32(arrayLength(&points));
    var uv = vec2<f32>(((mesh.uv.x*l)%20.0)/20.0, mesh.uv.y) ;
    return textureSample(base_color_texture, base_color_sampler, uv);
}