[PATCH v2 08/17] libcamera: vector: Extend matrix multiplication operator to heterogenous types
Kieran Bingham
kieran.bingham at ideasonboard.com
Mon Mar 31 19:09:46 CEST 2025
Quoting Stefan Klug (2025-03-19 16:11:13)
> From: Laurent Pinchart <laurent.pinchart at ideasonboard.com>
>
> It is useful to multiply matrices and vectors of heterogeneous types, for
> instance float and double. Extend the multiplication operator to support
> this, avoiding the need to convert one of the operations. The type of the
> returned vector is selected automatically to avoid loosing precision.
>
> Signed-off-by: Laurent Pinchart <laurent.pinchart at ideasonboard.com>
> Signed-off-by: Stefan Klug <stefan.klug at ideasonboard.com>
>
> Changes in v2:
> - Added this patch
I hope there's some tests added for these ;-)
Acked-by: Kieran Bingham <kieran.bingham at ideasonboard.com>
> ---
> include/libcamera/internal/vector.h | 9 +++++----
> src/libcamera/vector.cpp | 5 +++--
> 2 files changed, 8 insertions(+), 6 deletions(-)
>
> diff --git a/include/libcamera/internal/vector.h b/include/libcamera/internal/vector.h
> index 66cc5ac988c2..d518de9689a3 100644
> --- a/include/libcamera/internal/vector.h
> +++ b/include/libcamera/internal/vector.h
> @@ -13,6 +13,7 @@
> #include <numeric>
> #include <optional>
> #include <ostream>
> +#include <type_traits>
>
> #include <libcamera/base/log.h>
> #include <libcamera/base/span.h>
> @@ -295,13 +296,13 @@ private:
> template<typename T>
> using RGB = Vector<T, 3>;
>
> -template<typename T, unsigned int Rows, unsigned int Cols>
> -Vector<T, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<T, Cols> &v)
> +template<typename T, typename U, unsigned int Rows, unsigned int Cols>
> +Vector<std::common_type_t<T, U>, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<U, Cols> &v)
> {
> - Vector<T, Rows> result;
> + Vector<std::common_type_t<T, U>, Rows> result;
>
> for (unsigned int i = 0; i < Rows; i++) {
> - T sum = 0;
> + std::common_type_t<T, U> sum = 0;
> for (unsigned int j = 0; j < Cols; j++)
> sum += m[i][j] * v[j];
> result[i] = sum;
> diff --git a/src/libcamera/vector.cpp b/src/libcamera/vector.cpp
> index 435f2fc62f8b..c9419da8c663 100644
> --- a/src/libcamera/vector.cpp
> +++ b/src/libcamera/vector.cpp
> @@ -308,9 +308,10 @@ LOG_DEFINE_CATEGORY(Vector)
> */
>
> /**
> - * \fn Vector<T, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<T, Cols> &v)
> + * \fn operator*(const Matrix<T, Rows, Cols> &m, const Vector<U, Cols> &v)
> * \brief Multiply a matrix by a vector
> - * \tparam T Numerical type of the contents of the matrix and vector
> + * \tparam T Numerical type of the contents of the matrix
> + * \tparam U Numerical type of the contents of the vector
> * \tparam Rows The number of rows in the matrix
> * \tparam Cols The number of columns in the matrix (= rows in the vector)
> * \param m The matrix
> --
> 2.43.0
>
More information about the libcamera-devel
mailing list