From f6cca325dddbe847bd61030cbaaa3af96e36490c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Tue, 23 Apr 2019 18:08:02 +0200 Subject: [PATCH] python: make vectors implicitly convertible from tuples. --- src/python/magnum/math.vector.h | 15 +++++++++++++++ src/python/magnum/test/test_math.py | 6 +++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/python/magnum/math.vector.h b/src/python/magnum/math.vector.h index 886a62d..94c9407 100644 --- a/src/python/magnum/math.vector.h +++ b/src/python/magnum/math.vector.h @@ -110,9 +110,14 @@ template void vector(py::module& m, py::class_& c) { } template void vector2(py::class_>& c) { + py::implicitly_convertible&, Math::Vector2>(); + c /* Constructors */ .def(py::init(), "Constructor") + .def(py::init([](const std::tuple& value) { + return Math::Vector2{std::get<0>(value), std::get<1>(value)}; + }), "Construct from a tuple") /* Static constructors */ .def_static("x_axis", &Math::Vector2::xAxis, @@ -140,9 +145,14 @@ template void vector2(py::class_>& c) { } template void vector3(py::class_>& c) { + py::implicitly_convertible&, Math::Vector3>(); + c /* Constructors */ .def(py::init(), "Constructor") + .def(py::init([](const std::tuple& value) { + return Math::Vector3{std::get<0>(value), std::get<1>(value), std::get<2>(value)}; + }), "Construct from a tuple") /* Static constructors */ .def_static("x_axis", &Math::Vector3::xAxis, @@ -192,9 +202,14 @@ template void vector3(py::class_>& c) { } template void vector4(py::class_>& c) { + py::implicitly_convertible&, Math::Vector4>(); + c /* Constructors */ .def(py::init(), "Constructor") + .def(py::init([](const std::tuple& value) { + return Math::Vector4{std::get<0>(value), std::get<1>(value), std::get<2>(value), std::get<3>(value)}; + }), "Construct from a tuple") /* Properties */ .def_property("x", diff --git a/src/python/magnum/test/test_math.py b/src/python/magnum/test/test_math.py index 08de790..9450356 100644 --- a/src/python/magnum/test/test_math.py +++ b/src/python/magnum/test/test_math.py @@ -112,9 +112,13 @@ class Vector(unittest.TestCase): a = Vector4i() b = Vector3d.zero_init() c = Vector2i(44, -3) + d = Vector3((1.0, 0.3, 1.1)) + e = Vector4d((1.0, 0.3, 1.1, 0.5)) self.assertEqual(a, Vector4i(0, 0, 0, 0)) self.assertEqual(b, Vector3d(0.0, 0.0, 0.0)) self.assertEqual(c, Vector2i(44, -3)) + self.assertEqual(d, Vector3(1.0, 0.3, 1.1)) + self.assertEqual(e, Vector4d(1.0, 0.3, 1.1, 0.5)) def test_static_methods(self): self.assertEqual(Vector2.y_scale(5), Vector2(1, 5)) @@ -220,7 +224,7 @@ class Vector(unittest.TestCase): b = Vector4i(3, 4, 5, 6) b.b *= 3 - b.xy += Vector2i(1, -1) + b.xy += (1, -1) self.assertEqual(b, Vector4i(4, 3, 15, 6)) def test_iterate(self):