
#include "bkgr.hh"

#include <algorithm>

#include "itty/paths.hh"

#include "strings.hh"

void Bkgr::add_tiles(const std::filesystem::path& path, size_t w, size_t h)
{
        atlas.load(path, w, h);
        atlas.save_png(itty::paths.state.w(basedir / "bkgr.png"));
}

void Bkgr::upload(const itty::Box& view)
{
        renderer.clear();
        size_t x0 = std::clamp<int>(view.l / 8, 0, width());
        size_t x1 = std::clamp<int>(view.r / 8, 0, width());
        size_t y0 = std::clamp<int>(view.u / 8, 0, height());
        size_t y1 = std::clamp<int>(view.d / 8, 0, height());
        for (size_t y = y0; y != y1; ++y)
                for (size_t x = x0; x != x1; ++x) {
                        auto t = at(x, y);
                        if (t > 0) {
                                auto i = (t - 1) & 0xffff;
                                itty::Mat m;
                                m *= itty::Mat::translate(itty::Vec(x + 0.5, y + 0.5) * 8);
                                if (t & 0x80000000) m *= itty::Mat::scale(-1, 1);
                                if (t & 0x40000000) m *= itty::Mat::scale(1, -1);
                                if (t & 0x20000000) m *= itty::Mat{0, 1, 0, 1, 0, 0};
                                renderer.push(i, m);
                        }
                }
        renderer.upload();
}

void Bkgr::render(const itty::Box& view)
{
        renderer.render(view);
}

