7#ifndef PXR_BASE_VT_WRAP_ARRAY_H
8#define PXR_BASE_VT_WRAP_ARRAY_H
11#include "pxr/base/vt/api.h"
14#include "pxr/base/vt/value.h"
15#include "pxr/base/vt/pyOperators.h"
21#include "pxr/base/gf/traits.h"
23#include "pxr/base/tf/pyFunction.h"
24#include "pxr/base/tf/pyLock.h"
25#include "pxr/base/tf/pyObjWrapper.h"
26#include "pxr/base/tf/pyResultConversions.h"
29#include "pxr/base/tf/meta.h"
33#include "pxr/base/tf/wrapTypeHelpers.h"
35#include "pxr/external/boost/python/class.hpp"
36#include "pxr/external/boost/python/copy_const_reference.hpp"
37#include "pxr/external/boost/python/def.hpp"
38#include "pxr/external/boost/python/detail/api_placeholder.hpp"
39#include "pxr/external/boost/python/extract.hpp"
40#include "pxr/external/boost/python/implicit.hpp"
41#include "pxr/external/boost/python/iterator.hpp"
42#include "pxr/external/boost/python/make_constructor.hpp"
43#include "pxr/external/boost/python/object.hpp"
44#include "pxr/external/boost/python/operators.hpp"
45#include "pxr/external/boost/python/return_arg.hpp"
46#include "pxr/external/boost/python/slice.hpp"
47#include "pxr/external/boost/python/type_id.hpp"
48#include "pxr/external/boost/python/overloads.hpp"
57PXR_NAMESPACE_OPEN_SCOPE
59namespace Vt_WrapArray {
61using namespace pxr_boost::python;
69getitem_ellipsis(
VtArray<T> const &self,
object idx)
71 object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
72 if (idx != ellipsis) {
73 PyErr_SetString(PyExc_TypeError,
"unsupported index type");
74 throw_error_already_set();
81getitem_index(
VtArray<T> const &self, int64_t idx)
83 static const bool throwError =
true;
85 return object(self[idx]);
90getitem_slice(
VtArray<T> const &self, slice idx)
93 slice::range<typename VtArray<T>::const_iterator> range =
94 idx.get_indices(self.
begin(), self.
end());
95 const size_t setSize = 1 + (range.stop - range.start) / range.step;
98 for (; range.start != range.stop; range.start += range.step, ++i) {
99 result[i] = *range.start;
101 result[i] = *range.start;
102 return object(result);
104 catch (std::invalid_argument
const &) {
109template <
typename T,
typename S>
112 slice::range<T*>& range,
size_t setSize,
bool tile =
false)
115 const size_t length = len(value);
118 if (!tile && length < setSize) {
120 (
"Not enough values to set slice. Expected %zu, got %zu.",
127 std::vector<T> extracted;
128 extract<std::vector<T> > vectorExtraction(value);
129 if (vectorExtraction.check()) {
130 std::vector<T> tmp = vectorExtraction();
134 extracted.reserve(length);
135 for (
size_t i = 0; i != length; ++i) {
136 extracted.push_back(extract<T>(value[i]));
142 if (range.step == 1 && length >= setSize) {
143 std::copy(extracted.begin(), extracted.begin() + setSize, range.start);
146 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
147 *range.start = extracted[i % length];
154setArraySlice(
VtArray<T> &self, slice idx,
object value,
bool tile =
false)
157 slice::range<T*> range;
159 T* data = self.
data();
160 range = idx.get_indices(data, data + self.
size());
162 catch (std::invalid_argument
const &) {
168 const size_t setSize = 1 + (range.stop - range.start) / range.step;
176 const VtArray<T> val = extract< VtArray<T> >(value);
177 const size_t length = val.
size();
180 if (!tile && length < setSize) {
182 (
"Not enough values to set slice. Expected %zu, got %zu.",
188 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
189 *range.start = val[i % length];
194 else if (extract<T>(value).check()) {
201 const T val = extract<T>(value);
202 for (
size_t i = 0; i != setSize; range.start += range.step, ++i) {
208 else if (extract<list>(value).check()) {
209 setArraySlice(self, extract<list>(value)(), range, setSize, tile);
213 else if (extract<tuple>(value).check()) {
214 setArraySlice(self, extract<tuple>(value)(), range, setSize, tile);
219 setArraySlice(self, list(value), range, setSize, tile);
226setitem_ellipsis(
VtArray<T> &self,
object idx,
object value)
228 object ellipsis = object(handle<>(borrowed(Py_Ellipsis)));
229 if (idx != ellipsis) {
230 PyErr_SetString(PyExc_TypeError,
"unsupported index type");
231 throw_error_already_set();
233 setArraySlice(self, slice(0, self.
size()), value);
238setitem_index(
VtArray<T> &self, int64_t idx,
object value)
241 setArraySlice(self, slice(idx, idx+1), value,
true);
246setitem_slice(
VtArray<T> &self, slice idx,
object value)
248 setArraySlice(self, idx, value);
253VT_API
string GetVtArrayName();
255template <
class T,
class... Ts>
256constexpr bool Vt_IsAnySameImpl(TfMetaList<Ts...>) {
257 return (std::is_same_v<T, Ts> || ...);
260template <
class T,
class TypeList>
261constexpr bool Vt_IsAnySame() {
262 return Vt_IsAnySameImpl<T>(TypeList{});
267using Vt_OptimizedStreamIntegralTypes =
268 TfMetaList<short,
unsigned short,
271 long long,
unsigned long long>;
278inline bool _IsFinite(T
const &value) {
279 return std::isfinite(value);
281inline bool _IsFinite(
GfHalf const &value) {
282 return std::isfinite(
static_cast<float>(value));
286static void streamValue(std::ostringstream &stream, T
const &value) {
289 if constexpr(Vt_IsAnySame<T, Vt_OptimizedStreamIntegralTypes>()) {
294 if (_IsFinite(value)) {
307Vt_ComputeEffectiveRankAndLastDimSize(
308 Vt_ShapeData
const *sd,
size_t *lastDimSize)
310 unsigned int rank = sd->GetRank();
314 size_t divisor = std::accumulate(
315 sd->otherDims, sd->otherDims + rank-1,
316 1, [](
size_t x,
size_t y) { return x * y; });
318 size_t remainder = divisor ? sd->totalSize % divisor : 0;
319 *lastDimSize = divisor ? sd->totalSize / divisor : 0;
334 std::ostringstream stream;
335 stream.precision(17);
337 for (
size_t i = 0; i < self.
size(); ++i) {
338 stream << (i ?
", " :
"");
339 streamValue(stream, self[i]);
341 stream << (self.
size() == 1 ?
",)" :
")");
346 self.
size(), stream.str().c_str());
355 Vt_ShapeData
const *shapeData = self._GetShapeData();
356 size_t lastDimSize = 0;
358 Vt_ComputeEffectiveRankAndLastDimSize(shapeData, &lastDimSize);
360 std::string shapeStr =
"(";
361 for (
size_t i = 0; i != rank-1; ++i) {
363 i ?
", %d" :
"%d", shapeData->otherDims[i]);
367 repr.c_str(), shapeStr.c_str());
374VtArray<T> *VtArray__init__(
object const &values)
377 unique_ptr<VtArray<T> > ret(
new VtArray<T>(len(values)));
381 static const bool tile =
true;
382 setArraySlice(*ret, slice(0, ret->size()), values, tile);
383 return ret.release();
386VtArray<T> *VtArray__init__2(
size_t size,
object const &values)
389 unique_ptr<VtArray<T> > ret(
new VtArray<T>(size));
393 static const bool tile =
true;
394 setArraySlice(*ret, slice(0, ret->size()), values, tile);
396 return ret.release();
402ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
403ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
405VTOPERATOR_WRAP(__add__,__radd__)
406VTOPERATOR_WRAP_NONCOMM(__sub__,__rsub__)
407VTOPERATOR_WRAP(__mul__,__rmul__)
408VTOPERATOR_WRAP_NONCOMM(__div__,__rdiv__)
409VTOPERATOR_WRAP_NONCOMM(__mod__,__rmod__)
415static std::string _VtStr(T
const &self)
423 using namespace Vt_WrapArray;
426 typedef typename This::ElementType Type;
428 string name = GetVtArrayName<This>();
430 string docStr =
TfStringPrintf(
"An array of type %s.", typeStr.c_str());
432 auto selfCls = class_<This>(name.c_str(), docStr.c_str(), no_init)
433 .setattr(
"_isVtArray",
true)
436 .def(
"__init__", make_constructor(VtArray__init__<Type>),
438 "__init__(values)\n\n"
439 "values: a sequence (tuple, list, or another VtArray with "
440 "element type convertible to the new array's element type)\n\n"
442 .def(
"__init__", make_constructor(VtArray__init__2<Type>))
443 .def(init<unsigned int>())
445 .def(
"__getitem__", getitem_ellipsis<Type>)
446 .def(
"__getitem__", getitem_slice<Type>)
447 .def(
"__getitem__", getitem_index<Type>)
448 .def(
"__setitem__", setitem_ellipsis<Type>)
449 .def(
"__setitem__", setitem_slice<Type>)
450 .def(
"__setitem__", setitem_index<Type>)
452 .def(
"__len__", &This::size)
453 .def(
"__iter__", iterator<This>())
455 .def(
"__repr__", __repr__<Type>)
458 .def(
"__str__", _VtStr<T>)
462#ifdef NUMERIC_OPERATORS
463#define ADDITION_OPERATOR
464#define SUBTRACTION_OPERATOR
465#define MULTIPLICATION_OPERATOR
466#define DIVISION_OPERATOR
467#define UNARY_NEG_OPERATOR
470#ifdef ADDITION_OPERATOR
471 VTOPERATOR_WRAPDECLARE(+,__add__,__radd__)
473#ifdef SUBTRACTION_OPERATOR
474 VTOPERATOR_WRAPDECLARE(-,__sub__,__rsub__)
476#ifdef MULTIPLICATION_OPERATOR
477 VTOPERATOR_WRAPDECLARE(*,__mul__,__rmul__)
479#ifdef DIVISION_OPERATOR
480 VTOPERATOR_WRAPDECLARE(/,__div__,__rdiv__)
483 VTOPERATOR_WRAPDECLARE(%,__mod__,__rmod__)
485#ifdef DOUBLE_MULT_OPERATOR
486 .def(self *
double())
487 .def(
double() * self)
489#ifdef DOUBLE_DIV_OPERATOR
490 .def(self /
double())
492#ifdef UNARY_NEG_OPERATOR
499 TfPyContainerConversions::from_python_sequence<
501 TfPyContainerConversions::
502 variable_capacity_all_items_convertible_policy>();
505 implicitly_convertible<This, TfSpan<Type> >();
506 implicitly_convertible<This, TfSpan<const Type> >();
509template <
class Array>
513 typedef typename Array::ElementType ElemType;
515 if (PySequence_Check(obj.
ptr())) {
516 Py_ssize_t len = PySequence_Length(obj.
ptr());
518 ElemType *elem = result.data();
519 for (Py_ssize_t i = 0; i != len; ++i) {
520 pxr_boost::python::handle<> h(PySequence_ITEM(obj.
ptr(), i));
522 if (PyErr_Occurred())
526 pxr_boost::python::extract<ElemType> e(h.get());
532 }
else if (PyIter_Check(obj.
ptr())) {
534 while (PyObject *item = PyIter_Next(obj.
ptr())) {
535 pxr_boost::python::handle<> h(item);
537 if (PyErr_Occurred())
541 pxr_boost::python::extract<ElemType> e(h.get());
544 result.push_back(e());
551template <
class Array,
class Iter>
553Vt_ConvertFromRange(Iter begin, Iter end)
555 typedef typename Array::ElementType ElemType;
556 Array result(distance(begin, end));
557 for (ElemType *e = result.data(); begin != end; ++begin) {
558 VtValue cast = VtValue::Cast<ElemType>(*begin);
568Vt_CastToArray(
VtValue const &v) {
574 }
else if (v.
IsHolding<std::vector<VtValue> >()) {
575 std::vector<VtValue>
const &vec = v.
UncheckedGet<std::vector<VtValue> >();
576 ret = Vt_ConvertFromRange<T>(vec.begin(), vec.end());
583void VtRegisterValueCastsFromPythonSequencesToArray()
586 VtValue::RegisterCast<TfPyObjWrapper, Array>(Vt_CastToArray<Array>);
587 VtValue::RegisterCast<std::vector<VtValue>, Array>(Vt_CastToArray<Array>);
590#define VT_WRAP_ARRAY(unused, elem) \
591 VtWrapArray< VtArray< VT_TYPE(elem) > >();
593PXR_NAMESPACE_CLOSE_SCOPE
Architecture-specific math function calls.
A simple iterator adapter for STL containers.
Miscellaneous Utilities for dealing with script.
#define TF_PY_REPR_PREFIX
A macro which expands to the proper repr prefix for a library.
TF_API void TfPyThrowValueError(const char *msg)
Raises a Python ValueError with the given error msg and throws a pxr_boost::python::error_already_set...
TF_API int64_t TfPyNormalizeIndex(int64_t index, uint64_t size, bool throwError=false)
Return a positive index in the range [0,size).
std::string TfPyRepr(T const &t)
Return repr(t).
Defines all the types "TYPED" for which Vt creates a VtTYPEDArray typedef.
Convenience class for accessing the Python Global Interpreter Lock.
Boost Python object wrapper.
TF_API PyObject * ptr() const
Underlying PyObject* access.
Represents an arbitrary dimensional rectangular container class.
Provides a container which may hold any type, and provides introspection and iteration over array typ...
bool IsEmpty() const
Returns true iff this value is empty.
VtValue & Swap(VtValue &rhs) noexcept
Swap this with rhs.
bool IsHolding() const
Return true if this value is holding an object of type T, false otherwise.
T const & UncheckedGet() const &
Returns a const reference to the held object if the held object is of type T.
size_t size() const
Return the total number of elements in this array.
pointer data()
Return a non-const pointer to this array's data.
bool empty() const
Return true if this array contains no elements, false otherwise.
iterator end()
Returns a non-const iterator to the end of the array.
iterator begin()
Return a non-const iterator to the start of the array.
std::string ArchGetDemangled()
Return demangled RTTI generated-type name.
std::string TfStringify(const T &v)
Convert an arbitrary type into a string.
TF_API std::string TfStringPrintf(const char *fmt,...)
Returns a string formed by a printf()-like specification.
This header serves to simply bring in the half float datatype and provide a hash_value function.
pxr_half::half GfHalf
A 16-bit floating point data type.
Pragmas for controlling compiler-specific behaviors.
Utilities for providing C++ <-> Python container support.
Definitions of basic string utilities in tf.
A metafunction which is equivalent to std::is_floating_point but allows for additional specialization...
A boost.python visitor that associates the Python class object created by the wrapping with the TfTyp...
A file containing basic constants and definitions.