/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <gfx/gfx.h>
#include <gfx/private.h>
#include <stddef.h>

static unsigned int 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 = sizeof (struct gfx_rect)
            + (SCREEN_W / 10) * sizeof (struct gfx_sprite),
        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 = new_sz;
    }
    else
        return NULL;

    return ret;
}

struct gfx_sprite *gfx_sprite_get(void)
{
    return get_element(sizeof (struct gfx_sprite));
}

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

struct gfx_rect *gfx_rect_get(void)
{
    return get_element(sizeof (struct gfx_rect));
}

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