#pragma once

#if defined( __EMSCRIPTEN__ ) || defined( __ANDROID__ )
#include <GLES3/gl3.h>
#else
#include <glad/glad.h>
#endif

#include "crArray.h"
#include "crStruct.h"

// thick anti-aliased lines in pixel space — a quad per segment, shaded as a capsule SDF by
// line2d.frag (round caps fill the corners, so there is no miter math).
// GL_LINES is not an option: ES 3.0 only guarantees glLineWidth 1.0 and WebGL2 clamps it outright
class crBatchedLines2D
{
private:
    // interleaved vertex stream — must match line2d.vert locations 0..3
    struct LineVertex
    {
        float2 pos;         // pixel space
        color4 color;
        float2 p0;          // location 2 reads vec4( p0.xy, p1.xy ), so these two must stay adjacent
        float2 p1;
        float  halfWidth;   // pixels
    };
    static_assert( sizeof( LineVertex ) == 44, "LineVertex gained padding — the attrib pointers hardcode its offsets" );

    static constexpr int32_t INITIAL_RESERVE = 1024;
    static constexpr float   AA_MARGIN       = 1.0f;   // feather the quad has to leave room for

    crArray<LineVertex> _verts;

    GLuint _vao = 0;
    GLuint _vbo = 0;

public:
    void Init();
    void Cleanup();

    void Begin();
    void Line( float2 a, float2 b, float halfWidth, color4 color );   // pixel space; a == b is dropped
    void Flush( GLuint program, float4x4 proj );
    void ClearUnusedMemory();

private:
    void AddVertex( float2 pos, float2 p0, float2 p1, float halfWidth, color4 color );
};
