python/render.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | /// @file render.cpp | ||
| 3 | /// @brief Python bindings of the renderer: a scene's render settings rendered to a NumPy image. | ||
| 4 | #include "ernie/python/render.h" | ||
| 5 | |||
| 6 | #include "ernie/render/renderer.h" | ||
| 7 | |||
| 8 | #include <nanobind/ndarray.h> | ||
| 9 | #include <nanobind/stl/string.h> | ||
| 10 | |||
| 11 | #include <array> | ||
| 12 | #include <string> | ||
| 13 | |||
| 14 | namespace nb = nanobind; | ||
| 15 | |||
| 16 | namespace ernie::python { | ||
| 17 | |||
| 18 | 6 | void BindRender(nb::module_& module) { | |
| 19 | 6 | nb::class_<Renderer>(module, "Renderer", | |
| 20 | "A device and what it keeps of the scene it last rendered, so rendering " | ||
| 21 | "the same scene again costs only what changed.") | ||
| 22 | 6 | .def( | |
| 23 | "__init__", | ||
| 24 | 1 | [](Renderer* self, const std::string& device, bool validation) { | |
| 25 | 1 | new (self) Renderer(RendererOptions{.device = device, .validation = validation}); | |
| 26 | 1 | }, | |
| 27 | 24 | nb::kw_only(), nb::arg("device") = "", nb::arg("validation") = false, | |
| 28 | "Opens a device that ray traces: by UUID or part of its name, or the best one.") | ||
| 29 | 6 | .def( | |
| 30 | "render", | ||
| 31 | 1 | [](Renderer& self, const Scene& scene) { | |
| 32 | // The array owns the rendered tensor, so its bytes are copied once, off the device. | ||
| 33 | 1 | auto* image = new Tensor(self.Render(scene)); | |
| 34 | 1 | const nb::capsule owner( | |
| 35 | 1 | image, [](void* tensor) noexcept { delete static_cast<Tensor*>(tensor); }); | |
| 36 | 1 | const std::vector<std::int64_t>& shape = image->Shape(); | |
| 37 | 1 | const std::array<std::size_t, 3> dimensions{static_cast<std::size_t>(shape[0]), | |
| 38 | 1 | static_cast<std::size_t>(shape[1]), | |
| 39 | 1 | static_cast<std::size_t>(shape[2])}; | |
| 40 | 1 | return nb::ndarray<nb::numpy, std::uint8_t, nb::ndim<3>>( | |
| 41 | 1 | static_cast<std::uint8_t*>(image->Data()), 3, dimensions.data(), owner); | |
| 42 | 1 | }, | |
| 43 | 12 | nb::arg("scene"), | |
| 44 | "Renders the camera of the scene's first RenderSettings at its resolution: LdrColor " | ||
| 45 | "as a (height, width, 4) uint8 NumPy array."); | ||
| 46 | 6 | } | |
| 47 | |||
| 48 | } // namespace ernie::python | ||
| 49 |