diff --git a/quicktex/_bindings.cpp b/quicktex/_bindings.cpp index 63d104e..efb6b9a 100644 --- a/quicktex/_bindings.cpp +++ b/quicktex/_bindings.cpp @@ -101,12 +101,20 @@ PYBIND11_MODULE(_quicktex, m) { py::class_ raw_texture(m, "RawTexture", texture); raw_texture.def(py::init(), "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 pnt) { + int x, y; + PyIndex2D(pnt, t.Dimensions(), x, y); + return t.GetPixel(x, y); + }); + raw_texture.def("__setitem__", [](RawTexture &t, std::tuple pnt, Color val) { + int x, y; + PyIndex2D(pnt, t.Dimensions(), x, y); + t.SetPixel(x, y, val); + }); raw_texture.def_static("frombytes", &BufferToTexture, "data"_a, "width"_a, "height"_a); -// InitS3TC(m); + // InitS3TC(m); } } // namespace quicktex::bindings \ No newline at end of file diff --git a/quicktex/_bindings.h b/quicktex/_bindings.h index 29bdc08..b205e65 100644 --- a/quicktex/_bindings.h +++ b/quicktex/_bindings.h @@ -43,7 +43,7 @@ template T BufferToTexture(py::buffer buf, int width, int height) { static_assert(std::is_constructible::value); auto info = buf.request(false); - auto output = T(width, height);//std::make_shared(width, height); + auto output = T(width, height); // std::make_shared(width, height); auto dst_size = output.Size(); if (info.format != py::format_descriptor::format()) throw std::runtime_error("Incompatible format in python buffer: expected a byte array."); @@ -60,6 +60,18 @@ template 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 pnt, std::tuple 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 py::class_> BindBlockTexture(py::module_& m, const char* name) { using BTex = BlockTexture; diff --git a/tests/test_texture.py b/tests/test_texture.py index 762fda4..0c96576 100644 --- a/tests/test_texture.py +++ b/tests/test_texture.py @@ -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)