improved texture indexing

This commit is contained in:
Andrew Cassidy 2021-03-29 22:56:25 -07:00
parent 22bbdeb7b8
commit bd454d9d20
3 changed files with 28 additions and 8 deletions

View File

@ -101,12 +101,20 @@ PYBIND11_MODULE(_quicktex, m) {
py::class_<RawTexture> raw_texture(m, "RawTexture", texture);
raw_texture.def(py::init<int, int>(), "width"_a, "height"_a);
raw_texture.def("get_pixel", &RawTexture::GetPixel);
raw_texture.def("set_pixel", &RawTexture::SetPixel);
raw_texture.def("__getitem__", [](RawTexture &t, std::tuple<int, int> pnt) {
int x, y;
PyIndex2D(pnt, t.Dimensions(), x, y);
return t.GetPixel(x, y);
});
raw_texture.def("__setitem__", [](RawTexture &t, std::tuple<int, int> pnt, Color val) {
int x, y;
PyIndex2D(pnt, t.Dimensions(), x, y);
t.SetPixel(x, y, val);
});
raw_texture.def_static("frombytes", &BufferToTexture<RawTexture>, "data"_a, "width"_a, "height"_a);
// InitS3TC(m);
// InitS3TC(m);
}
} // namespace quicktex::bindings

View File

@ -43,7 +43,7 @@ template <typename T> T BufferToTexture(py::buffer buf, int width, int height) {
static_assert(std::is_constructible<T, int, int>::value);
auto info = buf.request(false);
auto output = T(width, height);//std::make_shared<T>(width, height);
auto output = T(width, height); // std::make_shared<T>(width, height);
auto dst_size = output.Size();
if (info.format != py::format_descriptor<uint8_t>::format()) throw std::runtime_error("Incompatible format in python buffer: expected a byte array.");
@ -60,6 +60,18 @@ template <typename T> T BufferToTexture(py::buffer buf, int width, int height) {
return output;
}
inline int PyIndex(int val, int size) {
if (val < -size) throw std::range_error("index out of range");
if (val >= size) throw std::range_error("index out of range");
if (val < 0) return size + val;
return val;
}
inline void PyIndex2D(std::tuple<int, int> pnt, std::tuple<int, int> size, int& x, int& y) {
x = PyIndex(std::get<0>(pnt), std::get<0>(size));
y = PyIndex(std::get<1>(pnt), std::get<1>(size));
}
template <typename B> py::class_<BlockTexture<B>> BindBlockTexture(py::module_& m, const char* name) {
using BTex = BlockTexture<B>;

View File

@ -25,12 +25,12 @@ class TestRawTexture(unittest.TestCase):
color1 = (69, 13, 12, 0) # totally random color
color2 = (19, 142, 93, 44)
self.texture.set_pixel(0, 0, color1)
self.texture.set_pixel(self.width - 1, self.height - 1, color2)
self.texture[0, 0] = color1
self.texture[-1, -1] = color2
data = self.texture.tobytes()
self.assertEqual(self.texture.get_pixel(0, 0), color1)
self.assertEqual(self.texture.get_pixel(self.width - 1, self.height - 1), color2)
self.assertEqual(self.texture[0, 0], color1)
self.assertEqual(self.texture[-1, -1], color2)
self.assertEqual(tuple(data[0:4]), color1)
self.assertEqual(tuple(data[-4:]), color2)