#include "gui_bridge.h"
#include "../cpp/desktop_gui.hpp"
#include "../cpp/code_buffer.hpp"
#include "../cpp/raster3d.hpp"
#include <new>
#include <cstring>

using namespace gaspardos;
using namespace gaspardos::gui;
using namespace gaspardos::desktop;
using namespace gaspardos::graphics;

namespace
{
// No C++ exception is allowed to escape a BIND(C) call.
#define FN(name, args)           \
    extern "C" int64_t name args \
    try
#define END                       \
    catch (const std::bad_alloc&) \
    {                             \
        return -12;               \
    }                             \
    catch (...)                   \
    {                             \
        return -22;               \
    }
#define PTR(name, args)        \
    extern "C" void* name args \
    try
#define END_PTR   \
    catch (...)   \
    {             \
        return 0; \
    }
#define REQUIRE(p) \
    if (!(p))      \
    return -22
#define OBJ(type, name, pointer) \
    REQUIRE(pointer);            \
    type& name = *static_cast<type*>(pointer)

    int64_t copy(const std::string& text, char* out, int64_t capacity)
    {
        if (capacity < 0 || (capacity && !out))
            return -22;
        if (capacity)
        {
            std::size_t n =
                std::min<std::size_t>(text.size(), static_cast<std::size_t>(capacity - 1));
            std::memcpy(out, text.data(), n);
            out[n] = 0;
        }
        return text.size();
    }

    class FortranPainter : public Painter
    {
        int64_t window_;

    public:
        explicit FortranPainter(int64_t window) : window_(window)
        {
        }

        int64_t fill(int x, int y, int w, int h, uint32_t color)
        {
            GO64_Drawing d;
            std::memset(&d, 0, sizeof(d));
            d.x      = x;
            d.y      = y;
            d.width  = w;
            d.height = h;
            d.color  = color;
            return GO64_window_fill(window_, &d);
        }

        int64_t text(int x, int y, uint32_t color, const char* text)
        {
            GO64_Drawing d;
            std::memset(&d, 0, sizeof(d));
            d.x     = x;
            d.y     = y;
            d.color = color;
            std::strncpy(d.text, text, sizeof(d.text) - 1);
            return GO64_window_text(window_, &d);
        }
    };

    template <class T>
    struct Owned
    {
        NativeFileAccess access;
        T                value;

        Owned() : value(access)
        {
        }
    };

    typedef Owned<FileDialog>    Dialog;
    typedef Owned<FileExplorer>  Explorer;
    typedef Owned<DirectoryTree> Tree;

    bool modeValid(int mode)
    {
        return mode >= 0 && mode <= 2;
    }

    bool dimensions(int width, int height)
    {
        return width > 0 && height > 0 && width <= 1024 && height <= 1024;
    }

    bool pathWide(const char* path, std::wstring& wide)
    {
        std::string normalized = normalize(path);
        if (normalized.empty() || normalized.size() > 4095 || !toWide(normalized, wide))
            return false;
        for (std::size_t i = 0; i < wide.size(); ++i)
        {
            if (wide[i] < 32)
                return false;
            if (wide[i] == '/')
                wide[i] = '\\';
        }
        if (parentPath(normalized).empty())
            wide += L"\\";
        return true;
    }

    struct Presenter
    {
        int64_t      window;
        Framebuffer* source;
        uint32_t*    pixels;
        unsigned     width, height, col, row;
        int          x, y;

        explicit Presenter(int64_t w)
            : window(w), source(0), pixels(0), width(0), height(0), col(0), row(0), x(0), y(0)
        {
        }

        void cancel()
        {
            source = 0;
            pixels = 0;
            col = row = 0;
        }

        int64_t present(Framebuffer& f, int px, int py)
        {
            if (!f.width() || !f.height() || px < -4096 || py < -4096
                || px > 4096 - static_cast<int>(f.width())
                || py > 4096 - static_cast<int>(f.height()))
                return -22;
            if (source
                && (source != &f || pixels != f.pixels() || width != f.width()
                    || height != f.height() || x != px || y != py))
                return -16;
            if (!source)
            {
                source = &f;
                pixels = f.pixels();
                width  = f.width();
                height = f.height();
                x      = px;
                y      = py;
            }
            while (row < height)
            {
                GO64_Blit tile;
                tile.x      = x + col;
                tile.y      = y + row;
                tile.width  = std::min<unsigned>(256, width - col);
                tile.height = std::min<unsigned>(256, height - row);
                tile.stride = width;
                tile.format = GO64_BLIT_RGBX8888;
                tile.pixels = pixels + row * width + col;
                int64_t r   = GO64_window_blit(window, &tile);
                if (r < 0)
                {
                    if (r != -11)
                        cancel();
                    return r;
                }
                col += tile.width;
                if (col == width)
                {
                    col = 0;
                    row += tile.height;
                }
            }
            cancel();
            return 0;
        }
    };
}  // namespace

PTR(gof_widgets_new, (int32_t width, int32_t height))
{
    if (width <= 0 || height <= 0)
        return 0;
    return new Widgets(width, height);
}

END_PTR
FN(gof_widgets_delete, (void* ui))
{
    delete static_cast<Widgets*>(ui);
    return 0;
}

END FN(gof_widgets_add,
       (void*       ui,
        int32_t     kind,
        int32_t     id,
        int32_t     x,
        int32_t     y,
        int32_t     width,
        int32_t     height,
        const char* text,
        int32_t     parent))
{
    OBJ(Widgets, u, ui);
    REQUIRE(text);
    return u.add(Widget(static_cast<Kind>(kind), id, x, y, width, height, text, parent));
}

END FN(gof_widgets_text, (void* ui, int32_t id, const char* text))
{
    OBJ(Widgets, u, ui);
    REQUIRE(text);
    return u.setText(id, text);
}

END FN(gof_widgets_value, (void* ui, int32_t id, char* output, int64_t capacity))
{
    OBJ(Widgets, u, ui);
    const char* text = u.value(id);
    if (!text)
        return -9;
    return copy(text, output, capacity);
}

END FN(gof_widgets_event, (void* ui, const void* event))
{
    OBJ(Widgets, u, ui);
    REQUIRE(event);
    const GO64_Event& e = *static_cast<const GO64_Event*>(event);
    Event             v = { e.type, e.x, e.y, e.buttons, e.key };
    return u.event(v);
}

END FN(gof_widgets_dirty, (void* ui))
{
    OBJ(Widgets, u, ui);
    return u.dirty();
}

END FN(gof_widgets_paint, (void* ui, int64_t window))
{
    OBJ(Widgets, u, ui);
    ::FortranPainter p(window);
    return u.paint(p);
}

END

PTR(gof_dialog_new, (void))
{
    return new Dialog;
}

END_PTR
FN(gof_dialog_delete, (void* dialog))
{
    delete static_cast<Dialog*>(dialog);
    return 0;
}

END FN(gof_dialog_begin,
       (void* dialog, int32_t mode, const char* initial, const char* suggested, int32_t overwrite))
{
    OBJ(Dialog, d, dialog);
    REQUIRE(initial);
    REQUIRE(suggested);
    if (!modeValid(mode))
        return -22;
    d.value.begin(static_cast<FileExplorer::Mode>(mode), initial, suggested, overwrite != 0);
    return 0;
}

END FN(gof_dialog_event, (void* dialog, const void* event, int64_t ticks))
{
    OBJ(Dialog, d, dialog);
    REQUIRE(event);
    d.value.event(*static_cast<const GO64_Event*>(event), ticks);
    return 0;
}

END FN(gof_dialog_tick, (void* dialog))
{
    OBJ(Dialog, d, dialog);
    d.value.tick();
    return 0;
}

END FN(gof_dialog_paint, (void* dialog, int64_t window))
{
    OBJ(Dialog, d, dialog);
    ::FortranPainter p(window);
    return d.value.paint(p);
}

END FN(gof_dialog_active, (void* dialog))
{
    OBJ(Dialog, d, dialog);
    return d.value.active();
}

END FN(gof_dialog_accepted, (void* dialog))
{
    OBJ(Dialog, d, dialog);
    return d.value.accepted();
}

END FN(gof_dialog_result, (void* dialog, char* output, int64_t capacity))
{
    OBJ(Dialog, d, dialog);
    return copy(d.value.result(), output, capacity);
}

END

PTR(gof_input_new, (const char* text))
{
    return text ? new TextInput(text) : 0;
}

END_PTR
FN(gof_input_delete, (void* input))
{
    delete static_cast<TextInput*>(input);
    return 0;
}

END FN(gof_input_set, (void* input, const char* text))
{
    OBJ(TextInput, t, input);
    REQUIRE(text);
    t.set(text);
    return 0;
}

END FN(gof_input_key, (void* input, int32_t key))
{
    OBJ(TextInput, t, input);
    t.key(key);
    return 0;
}

END FN(gof_input_value, (void* input, char* output, int64_t capacity))
{
    OBJ(TextInput, t, input);
    return copy(t.value, output, capacity);
}

END FN(gof_input_visible,
       (void* input, int32_t columns, int32_t focused, char* output, int64_t capacity))
{
    OBJ(TextInput, t, input);
    if (columns < 0 || columns > 4096)
        return -22;
    return copy(t.visible(columns, focused != 0), output, capacity);
}

END PTR(gof_queue_new, (void) )
{
    return new PaintQueue;
}

END_PTR
FN(gof_queue_delete, (void* queue))
{
    delete static_cast<PaintQueue*>(queue);
    return 0;
}

END FN(gof_queue_clear, (void* queue))
{
    OBJ(PaintQueue, q, queue);
    q.clear();
    return 0;
}

END FN(gof_queue_fill,
       (void* queue, int32_t x, int32_t y, int32_t width, int32_t height, int32_t color))
{
    OBJ(PaintQueue, q, queue);
    q.fill(x, y, width, height, color);
    return 0;
}

END FN(gof_queue_text,
       (void* queue, int32_t x, int32_t y, const char* text, int32_t color, int32_t columns))
{
    OBJ(PaintQueue, q, queue);
    REQUIRE(text);
    if (columns <= 0 || columns > 4096)
        return -22;
    q.text(x, y, text, color, columns);
    return 0;
}

END FN(gof_queue_button,
       (void* queue, int32_t x, int32_t y, int32_t width, const char* text, int32_t selected))
{
    OBJ(PaintQueue, q, queue);
    REQUIRE(text);
    q.button(x, y, width, text, selected != 0);
    return 0;
}

END FN(gof_queue_input,
       (void* queue, int32_t x, int32_t y, int32_t width, void* input, int32_t focused))
{
    OBJ(PaintQueue, q, queue);
    REQUIRE(input);
    q.input(x, y, width, *static_cast<TextInput*>(input), focused != 0);
    return 0;
}

END FN(gof_queue_finished, (void* queue))
{
    OBJ(PaintQueue, q, queue);
    return q.finished();
}

END FN(gof_queue_paint, (void* queue, int64_t window))
{
    OBJ(PaintQueue, q, queue);
    ::FortranPainter p(window);
    return q.paint(p);
}

END

PTR(gof_explorer_new, (void))
{
    return new Explorer;
}

END_PTR
FN(gof_explorer_delete, (void* explorer))
{
    delete static_cast<Explorer*>(explorer);
    return 0;
}

END FN(gof_explorer_begin, (void* explorer, int32_t mode, const char* initial, int32_t overwrite))
{
    OBJ(Explorer, e, explorer);
    REQUIRE(initial);
    if (!modeValid(mode))
        return -22;
    e.value.begin(static_cast<FileExplorer::Mode>(mode), initial, overwrite != 0);
    return 0;
}

END FN(gof_explorer_navigate, (void* explorer, const char* path))
{
    OBJ(Explorer, e, explorer);
    REQUIRE(path);
    return e.value.navigate(path);
}

END FN(gof_explorer_tick, (void* explorer))
{
    OBJ(Explorer, e, explorer);
    return e.value.tick();
}

END FN(gof_explorer_select, (void* explorer, int32_t index))
{
    OBJ(Explorer, e, explorer);
    if (index < 0 || static_cast<std::size_t>(index) >= e.value.entries().size())
        return -22;
    e.value.select(index);
    return 0;
}

END FN(gof_explorer_activate, (void* explorer, int32_t index))
{
    OBJ(Explorer, e, explorer);
    if (index < 0 || static_cast<std::size_t>(index) >= e.value.entries().size())
        return -22;
    e.value.activate(index);
    return 0;
}

END FN(gof_explorer_accept, (void* explorer, const char* name))
{
    OBJ(Explorer, e, explorer);
    REQUIRE(name);
    return e.value.accept(name);
}

END FN(gof_explorer_mkdir, (void* explorer, const char* name))
{
    OBJ(Explorer, e, explorer);
    REQUIRE(name);
    return e.value.createFolder(name);
}

END FN(gof_explorer_cancel, (void* explorer))
{
    OBJ(Explorer, e, explorer);
    e.value.cancel();
    return 0;
}

END FN(gof_explorer_state, (void* explorer, int32_t field))
{
    OBJ(Explorer, e, explorer);
    switch (field)
    {
        case 0:
            return e.value.loading();
        case 1:
            return e.value.finished();
        case 2:
            return e.value.accepted();
        case 3:
            return e.value.confirming();
        case 4:
            return e.value.selected();
        case 5:
            return e.value.mode();
        case 6:
            return e.value.entries().size();
        case 7:
            return e.value.volumes.size();
        default:
            return -22;
    }
}

END FN(gof_explorer_text, (void* explorer, int32_t field, char* output, int64_t capacity))
{
    OBJ(Explorer, e, explorer);
    switch (field)
    {
        case 0:
            return copy(e.value.directory(), output, capacity);
        case 1:
            return copy(e.value.result(), output, capacity);
        case 2:
            return copy(e.value.message, output, capacity);
        default:
            return -22;
    }
}

END FN(
    gof_explorer_entry,
    (void* explorer, int32_t volume, int32_t index, int32_t field, char* output, int64_t capacity))
{
    OBJ(Explorer, e, explorer);
    if (volume < 0 || volume > 1)
        return -22;
    const std::vector<FileEntry>& entries = volume ? e.value.volumes : e.value.entries();
    if (index < 0 || static_cast<std::size_t>(index) >= entries.size() || field < 0 || field > 1)
        return -22;
    return copy(field ? entries[index].path : entries[index].name, output, capacity);
}

END FN(gof_explorer_info, (void* explorer, int32_t volume, int32_t index, int32_t field))
{
    OBJ(Explorer, e, explorer);
    if (volume < 0 || volume > 1)
        return -22;
    const std::vector<FileEntry>& entries = volume ? e.value.volumes : e.value.entries();
    if (index < 0 || static_cast<std::size_t>(index) >= entries.size() || field < 0 || field > 1)
        return -22;
    return field ? static_cast<int64_t>(entries[index].bytes) : entries[index].directory;
}

END PTR(gof_tree_new, (void) )
{
    return new Tree;
}

END_PTR
FN(gof_tree_delete, (void* tree))
{
    delete static_cast<Tree*>(tree);
    return 0;
}

END FN(gof_tree_open, (void* tree, const char* root))
{
    OBJ(Tree, t, tree);
    REQUIRE(root);
    return t.value.open(root);
}

END FN(gof_tree_toggle, (void* tree, int32_t index))
{
    OBJ(Tree, t, tree);
    if (index < 0 || static_cast<std::size_t>(index) >= t.value.rows.size())
        return -22;
    t.value.toggle(index);
    return 0;
}

END FN(gof_tree_tick, (void* tree))
{
    OBJ(Tree, t, tree);
    return t.value.tick();
}

END FN(gof_tree_state, (void* tree, int32_t field))
{
    OBJ(Tree, t, tree);
    if (field == 0)
        return t.value.loading();
    if (field == 1)
        return t.value.rows.size();
    return -22;
}

END FN(gof_tree_text, (void* tree, int32_t field, char* output, int64_t capacity))
{
    OBJ(Tree, t, tree);
    if (field < 0 || field > 1)
        return -22;
    return copy(field ? t.value.message : t.value.root(), output, capacity);
}

END FN(gof_tree_entry, (void* tree, int32_t index, int32_t field, char* output, int64_t capacity))
{
    OBJ(Tree, t, tree);
    if (index < 0 || static_cast<std::size_t>(index) >= t.value.rows.size() || field < 0
        || field > 1)
        return -22;
    const FileEntry& e = t.value.rows[index].entry;
    return copy(field ? e.path : e.name, output, capacity);
}

END FN(gof_tree_info, (void* tree, int32_t index, int32_t field))
{
    OBJ(Tree, t, tree);
    if (index < 0 || static_cast<std::size_t>(index) >= t.value.rows.size())
        return -22;
    const TreeRow& r = t.value.rows[index];
    switch (field)
    {
        case 0:
            return r.entry.directory;
        case 1:
            return r.entry.bytes;
        case 2:
            return r.depth;
        case 3:
            return r.expanded;
        default:
            return -22;
    }
}

END

FN(gof_fs_open, (const char* path, int64_t flags))
{
    REQUIRE(path);
    std::wstring wide;
    if (!pathWide(path, wide))
        return -22;
    return GO64_fs_open(wide.c_str(), flags);
}

END FN(gof_fs_stat, (const char* path, void* info))
{
    REQUIRE(path);
    REQUIRE(info);
    std::wstring wide;
    if (!pathWide(path, wide))
        return -22;
    return GO64_fs_stat(wide.c_str(), static_cast<GO64_FSInfo*>(info));
}

END FN(gof_fs_mkdir, (const char* path))
{
    REQUIRE(path);
    NativeFileAccess a;
    return a.mkdir(path);
}

END FN(gof_fs_remove, (const char* path))
{
    REQUIRE(path);
    NativeFileAccess a;
    return a.remove(path);
}

END FN(gof_fs_rename, (const char* from, const char* to))
{
    REQUIRE(from);
    REQUIRE(to);
    NativeFileAccess a;
    return a.rename(from, to);
}

END FN(gof_fs_read, (const char* path, void* output, int64_t capacity))
{
    REQUIRE(path);
    if (capacity < 0 || (capacity && !output))
        return -22;
    NativeFileAccess a;
    std::string      data;
    int64_t          r = a.read(path, data, capacity);
    if (r < 0)
        return r;
    if (data.size() > static_cast<uint64_t>(capacity))
        return -22;
    if (!data.empty())
        std::memcpy(output, data.data(), data.size());
    return data.size();
}

END FN(gof_fs_create, (const char* path, const void* data, int64_t size))
{
    REQUIRE(path);
    if (size < 0 || (size && !data))
        return -22;
    NativeFileAccess a;
    return a.create(path, std::string(size ? static_cast<const char*>(data) : "", size));
}

END FN(gof_fs_save,
       (const char* path,
        const void* data,
        int64_t     size,
        int32_t     overwrite,
        char*       message,
        int64_t     capacity))
{
    REQUIRE(path);
    if (size < 0 || (size && !data) || capacity < 0 || (capacity && !message))
        return -22;
    NativeFileAccess a;
    std::string      text;
    bool             ok = saveFile(a,
                       path,
                       std::string(size ? static_cast<const char*>(data) : "", size),
                       overwrite != 0,
                       text);
    copy(text, message, capacity);
    return ok;
}

END FN(gof_ipv4, (int32_t a, int32_t b, int32_t c, int32_t d, int32_t port, void* address))
{
    REQUIRE(address);
    if (a < 0 || a > 255 || b < 0 || b > 255 || c < 0 || c > 255 || d < 0 || d > 255 || port < 0
        || port > 65535)
        return -22;
    *static_cast<GO64_SocketAddress*>(address) = ipv4(a, b, c, d, port);
    return 0;
}

END

PTR(gof_code_new, (void))
{
    return new CodeBuffer;
}

END_PTR
FN(gof_code_delete, (void* code))
{
    delete static_cast<CodeBuffer*>(code);
    return 0;
}

END FN(gof_code_load, (void* code, const void* data, int64_t size, char* error, int64_t capacity))
{
    OBJ(CodeBuffer, c, code);
    if (size < 0 || (size && !data) || capacity < 0 || (capacity && !error))
        return -22;
    std::string message;
    bool        ok = c.load(std::string(size ? static_cast<const char*>(data) : "", size), message);
    copy(message, error, capacity);
    return ok;
}

END FN(gof_code_clear, (void* code))
{
    OBJ(CodeBuffer, c, code);
    c.clear();
    return 0;
}

END FN(gof_code_saved, (void* code))
{
    OBJ(CodeBuffer, c, code);
    c.saved();
    return 0;
}

END FN(gof_code_key, (void* code, int32_t key))
{
    OBJ(CodeBuffer, c, code);
    return c.key(key);
}

END FN(gof_code_undo, (void* code))
{
    OBJ(CodeBuffer, c, code);
    return c.undo();
}

END FN(gof_code_place, (void* code, int32_t row, int32_t column))
{
    OBJ(CodeBuffer, c, code);
    if (row < 0 || column < 0)
        return -22;
    c.place(row, column);
    return 0;
}

END FN(gof_code_state, (void* code, int32_t field))
{
    OBJ(CodeBuffer, c, code);
    switch (field)
    {
        case 0:
            return c.dirty();
        case 1:
            return c.lineCount();
        case 2:
            return c.row();
        case 3:
            return c.column();
        default:
            return -22;
    }
}

END FN(gof_code_text, (void* code, int32_t field, int32_t index, char* output, int64_t capacity))
{
    OBJ(CodeBuffer, c, code);
    switch (field)
    {
        case 0:
            return copy(c.serialize(), output, capacity);
        case 1:
            return copy(c.original(), output, capacity);
        case 2:
            if (index < 0 || static_cast<std::size_t>(index) >= c.lineCount())
                return -22;
            return copy(c.line(index), output, capacity);
        default:
            return -22;
    }
}

END

PTR(gof_framebuffer_new, (int32_t width, int32_t height))
{
    return dimensions(width, height) ? new Framebuffer(width, height) : 0;
}

END_PTR
FN(gof_framebuffer_delete, (void* framebuffer))
{
    delete static_cast<Framebuffer*>(framebuffer);
    return 0;
}

END FN(gof_framebuffer_resize, (void* framebuffer, int32_t width, int32_t height))
{
    OBJ(Framebuffer, f, framebuffer);
    if (!dimensions(width, height))
        return -22;
    return f.resize(width, height);
}

END FN(gof_framebuffer_width, (void* framebuffer))
{
    OBJ(Framebuffer, f, framebuffer);
    return f.width();
}

END FN(gof_framebuffer_height, (void* framebuffer))
{
    OBJ(Framebuffer, f, framebuffer);
    return f.height();
}

END PTR(gof_framebuffer_pixels, (void* framebuffer))
{
    return framebuffer ? static_cast<Framebuffer*>(framebuffer)->pixels() : 0;
}

END_PTR
FN(gof_framebuffer_clear, (void* framebuffer, int32_t color))
{
    OBJ(Framebuffer, f, framebuffer);
    f.clear(color);
    return 0;
}

END FN(gof_framebuffer_pixel, (void* framebuffer, int32_t x, int32_t y, int32_t color))
{
    OBJ(Framebuffer, f, framebuffer);
    f.pixel(x, y, color);
    return 0;
}

END FN(gof_framebuffer_get, (void* framebuffer, int32_t x, int32_t y))
{
    OBJ(Framebuffer, f, framebuffer);
    return f.pixel(x, y);
}

END FN(gof_framebuffer_circle,
       (void* framebuffer, int32_t x, int32_t y, int32_t radius, int32_t color))
{
    OBJ(Framebuffer, f, framebuffer);
    if (radius < 0 || radius > 1024)
        return -22;
    f.circle(x, y, radius, color);
    return 0;
}

END PTR(gof_presenter_new, (int64_t window))
{
    return window > 0 ? new Presenter(window) : 0;
}

END_PTR
FN(gof_presenter_delete, (void* presenter))
{
    delete static_cast<Presenter*>(presenter);
    return 0;
}

END FN(gof_presenter_present, (void* presenter, void* framebuffer, int32_t x, int32_t y))
{
    OBJ(Presenter, p, presenter);
    REQUIRE(framebuffer);
    return p.present(*static_cast<Framebuffer*>(framebuffer), x, y);
}

END FN(gof_presenter_pending, (void* presenter))
{
    OBJ(Presenter, p, presenter);
    return p.source != 0;
}

END FN(gof_presenter_cancel, (void* presenter))
{
    OBJ(Presenter, p, presenter);
    p.cancel();
    return 0;
}

END

PTR(gof_mesh_new, (void))
{
    return new Mesh;
}

END_PTR
FN(gof_mesh_delete, (void* mesh))
{
    delete static_cast<Mesh*>(mesh);
    return 0;
}

END FN(gof_mesh_vertex, (void* mesh, float x, float y, float z))
{
    OBJ(Mesh, m, mesh);
    m.vertices.push_back(Vec3(x, y, z));
    return m.vertices.size() - 1;
}

END FN(gof_mesh_triangle, (void* mesh, int32_t a, int32_t b, int32_t c, int32_t color))
{
    OBJ(Mesh, m, mesh);
    if (a < 0 || b < 0 || c < 0 || static_cast<std::size_t>(a) >= m.vertices.size()
        || static_cast<std::size_t>(b) >= m.vertices.size()
        || static_cast<std::size_t>(c) >= m.vertices.size())
        return -22;
    m.triangles.push_back(Triangle(a, b, c, color));
    return m.triangles.size() - 1;
}

END PTR(gof_shape, (int32_t kind, float a, float b, float c, int32_t slices, int32_t stacks))
{
    Mesh mesh;
    switch (kind)
    {
        case 1:
            mesh = Shapes3D::cube(a);
            break;
        case 2:
            mesh = Shapes3D::box(a, b, c);
            break;
        case 3:
            mesh = Shapes3D::pyramid(a, b);
            break;
        case 4:
            mesh = Shapes3D::plane(a, b);
            break;
        case 5:
            if (slices < 3 || slices > 128 || stacks < 2 || stacks > 128)
                return 0;
            mesh = Shapes3D::sphere(a, slices, stacks);
            break;
        case 6:
            if (slices < 3 || slices > 128)
                return 0;
            mesh = Shapes3D::cylinder(a, b, slices);
            break;
        default:
            return 0;
    }
    return new Mesh(mesh);
}

END_PTR
PTR(gof_raster_new, (void* framebuffer))
{
    return framebuffer ? new Rasterizer3D(*static_cast<Framebuffer*>(framebuffer)) : 0;
}

END_PTR
FN(gof_raster_delete, (void* raster))
{
    delete static_cast<Rasterizer3D*>(raster);
    return 0;
}

END FN(gof_raster_clear, (void* raster, int32_t color))
{
    OBJ(Rasterizer3D, r, raster);
    r.clear(color);
    return 0;
}

END FN(gof_raster_draw,
       (void*   raster,
        void*   mesh,
        float   rx,
        float   ry,
        float   rz,
        float   x,
        float   y,
        float   z,
        int32_t wireframe,
        int32_t hollow))
{
    OBJ(Rasterizer3D, r, raster);
    REQUIRE(mesh);
    Pose pose;
    pose.rotation    = Vec3(rx, ry, rz);
    pose.translation = Vec3(x, y, z);
    r.draw(*static_cast<Mesh*>(mesh), pose, wireframe != 0, hollow != 0);
    return 0;
}

END
