test.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #define _hypot hypot
  2. #include <cmath>
  3. #include <pybind11/pybind11.h>
  4. #include <string>
  5. #include <vector>
  6. namespace py = pybind11;
  7. int add(int i, int j) {
  8. return i + j;
  9. }
  10. enum class Orientation {
  11. DOWN = -1,
  12. NONE = 0,
  13. UP = 1,
  14. NOT_SET = 2,
  15. ANY = 3,
  16. DEFAULT = 4
  17. };
  18. #define POS_INVALID 0
  19. struct Vec3 {
  20. Vec3() = default;
  21. Vec3(const Vec3& a) { }
  22. Vec3(const float x_, const float y_, const float z_) { x = x_; y = y_; z = z_; }
  23. Vec3(const float xyz) { x = xyz; y = xyz; z = xyz; }
  24. Vec3(const std::vector<float>& xyz) { assert(xyz.size() == 3); x = xyz[0]; y = xyz[1]; z = xyz[2]; }
  25. bool is_valid() const { return !(x == POS_INVALID || y == POS_INVALID || z == POS_INVALID); }
  26. std::string to_string() const;
  27. void dump(const std::string extra_comment, const std::string ind) const;
  28. float x, y, z;
  29. };
  30. void define_pybinding_Vec3(py::module& m) {
  31. py::class_<Vec3>(m, "Vec3")
  32. .def(
  33. py::init<>()
  34. )
  35. .def(
  36. py::init<const float>(),
  37. py::arg("xyz")
  38. )
  39. .def(
  40. py::init<const float, const float, const float>(),
  41. py::arg("x"), py::arg("y"), py::arg("z")
  42. )
  43. .def("__add__", [](const Vec3& a, const Vec3& b) { return Vec3(a.x + b.x); } )
  44. .def("__sub__", [](const Vec3& a, const Vec3& b) { return Vec3(a.x - b.x); } )
  45. .def("__mul__", [](const Vec3& a, const Vec3& b) { return Vec3(a.x * b.x); } )
  46. .def("__truediv__", [](const Vec3& a, const Vec3& b) { return Vec3(a.x / b.x); } )
  47. .def("__eq__", [](const Vec3& a, const Vec3& b) { return a.x == b.x; } )
  48. .def("__str__", [](const Vec3& a)
  49. { return "(" + std::to_string(a.x) + ", " + std::to_string(a.y) + ", " + std::to_string(a.z) + ")"; } )
  50. .def("__repr__", [](const Vec3& a)
  51. { return "(" + std::to_string(a.x) + ", " + std::to_string(a.y) + ", " + std::to_string(a.z) + ")"; } )
  52. .def("to_list", [](const Vec3& a) { return std::vector<float>{a.x, a.y, a.z}; } )
  53. .def_readwrite("x", &Vec3::x)
  54. .def_readwrite("y", &Vec3::y)
  55. .def_readwrite("z", &Vec3::z)
  56. ;
  57. }
  58. PYBIND11_MODULE(mcell, m) {
  59. m.doc() = "pybind11 example plugin"; // optional module docstring
  60. py::enum_<Orientation>(m, "Orientation", py::arithmetic())
  61. .value("DOWN", Orientation::DOWN)
  62. .value("NONE", Orientation::NONE)
  63. .value("UP", Orientation::UP)
  64. .value("NOT_SET", Orientation::NOT_SET)
  65. .value("ANY", Orientation::ANY)
  66. .value("DEFAULT", Orientation::DEFAULT)
  67. .export_values();
  68. define_pybinding_Vec3(m);
  69. m.def("add", &add, "A function which adds two numbers");
  70. }