summaryrefslogtreecommitdiffhomepage
path: root/src/tile-atlas.cpp
blob: 50f28cd0ad6556583084eeb0f82a0a0c69e010fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "tile-atlas.hpp"
#include "compat/assert.hpp"
#include <Corrade/Containers/StringView.h>
#include <Magnum/Math/Color.h>
#include <Magnum/ImageView.h>
#include <Magnum/GL/TextureFormat.h>

namespace floormat {

tile_atlas::tile_atlas(Containers::StringView name, const ImageView2D& image, Vector2ui dims) :
    name_{name},
    size_{image.size()},
    dims_{dims}
{
    CORRADE_INTERNAL_ASSERT(dims_[0] > 0 && dims_[1] > 0);
    CORRADE_INTERNAL_ASSERT(size_ % dims_ == Vector2ui{});
    CORRADE_INTERNAL_ASSERT(dims_.product() < 256);
    tex_.setWrapping(GL::SamplerWrapping::ClampToEdge)
        .setMagnificationFilter(GL::SamplerFilter::Linear)
        .setMinificationFilter(GL::SamplerFilter::Linear)
        .setMaxAnisotropy(1)
        .setBorderColor(Color4{1, 0, 0, 1})
        .setStorage(1, GL::textureFormat(image.format()), image.size())
        .setSubImage(0, {}, image);
}

std::array<Vector2, 4> tile_atlas::texcoords_for_id(std::size_t id_) const
{
    const auto sz = size_/dims_;
    ASSERT(id_ < sz.product());
    const Vector2ui id = { (UnsignedInt)id_ % dims_[0], (UnsignedInt)id_ / dims_[0] };
    const Vector2 p0(id * sz), p1(sz);
    const auto x0 = p0.x(), x1 = p1.x()-1, y0 = p0.y(), y1 = p1.y()-1;
    return {{
        { (x0+x1)/size_[0], (y0+y1)/size_[1]  }, // bottom right
        { (x0+x1)/size_[0], y0/size_[1]       }, // top right
        { x0/size_[0],      (y0+y1)/size_[1]  }, // bottom left
        { x0/size_[0],      y0/size_[1]       }  // top left
    }};
}

} // namespace floormat