#include <gfx.h>
#include <gfx_private.h>
#include <stddef.h>

static unsigned sel;
static size_t heap_i;

void gfx_swapheap(void)
{
    sel ^= 1;
    heap_i = 0;
}

static void *get_element(const size_t sz)
{
    enum {HEAP_SZ = 6144, N_HEAPS = 2};
    static char heaps[N_HEAPS][HEAP_SZ];
    const size_t new_sz = heap_i + sz;
    void *ret = NULL;

    if (new_sz < sizeof *heaps / sizeof **heaps)
    {
        ret = &heaps[sel][heap_i];
        heap_i += sz;
    }
    else
    {
        fprintf(stderr, "%s: exceeded heap size (%zu/%zu)\n",
            __func__, new_sz, sizeof *heaps / sizeof **heaps);
        return NULL;
    }

    return ret;
}

struct sprite *sprite_get(void)
{
    return get_element(sizeof (struct sprite));
}

struct quad *quad_get(void)
{
    return get_element(sizeof (struct quad));
}

struct rect *rect_get(void)
{
    return get_element(sizeof (struct rect));
}

struct stp_4line *stp_4line_get(void)
{
    return get_element(sizeof (struct stp_4line));
}
