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)) {
308Vt_ComputeEffectiveRankAndLastDimSize(
309 Vt_ShapeData
const *sd,
size_t *lastDimSize);
318 std::ostringstream stream;
319 stream.precision(17);
321 for (
size_t i = 0; i < self.
size(); ++i) {
322 stream << (i ?
", " :
"");
323 streamValue(stream, self[i]);
325 stream << (self.
size() == 1 ?
",)" :
")");
330 self.
size(), stream.str().c_str());
339 Vt_ShapeData
const *shapeData = self._GetShapeData();
340 size_t lastDimSize = 0;
342 Vt_ComputeEffectiveRankAndLastDimSize(shapeData, &lastDimSize);
344 std::string shapeStr =
"(";
345 for (
size_t i = 0; i != rank-1; ++i) {
347 i ?
", %d" :
"%d", shapeData->otherDims[i]);
351 repr.c_str(), shapeStr.c_str());
358VtArray<T> *VtArray__init__(
object const &values)
361 unique_ptr<VtArray<T> > ret(
new VtArray<T>(len(values)));
365 static const bool tile =
true;
366 setArraySlice(*ret, slice(0, ret->size()), values, tile);
367 return ret.release();
370VtArray<T> *VtArray__init__2(
size_t size,
object const &values)
373 unique_ptr<VtArray<T> > ret(
new VtArray<T>(size));
377 static const bool tile =
true;
378 setArraySlice(*ret, slice(0, ret->size()), values, tile);
380 return ret.release();
386ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
387ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
389VTOPERATOR_WRAP(__add__,__radd__)
390VTOPERATOR_WRAP_NONCOMM(__sub__,__rsub__)
391VTOPERATOR_WRAP(__mul__,__rmul__)
392VTOPERATOR_WRAP_NONCOMM(__div__,__rdiv__)
393VTOPERATOR_WRAP_NONCOMM(__mod__,__rmod__)
399static std::string _VtStr(T
const &self)
407 using namespace Vt_WrapArray;
410 typedef typename This::ElementType Type;
412 string name = GetVtArrayName<This>();
414 string docStr =
TfStringPrintf(
"An array of type %s.", typeStr.c_str());
416 auto selfCls = class_<This>(name.c_str(), docStr.c_str(), no_init)
417 .setattr(
"_isVtArray",
true)
420 .def(
"__init__", make_constructor(VtArray__init__<Type>),
422 "__init__(values)\n\n"
423 "values: a sequence (tuple, list, or another VtArray with "
424 "element type convertible to the new array's element type)\n\n"
426 .def(
"__init__", make_constructor(VtArray__init__2<Type>))
427 .def(init<unsigned int>())
429 .def(
"__getitem__", getitem_ellipsis<Type>)
430 .def(
"__getitem__", getitem_slice<Type>)
431 .def(
"__getitem__", getitem_index<Type>)
432 .def(
"__setitem__", setitem_ellipsis<Type>)
433 .def(
"__setitem__", setitem_slice<Type>)
434 .def(
"__setitem__", setitem_index<Type>)
436 .def(
"__len__", &This::size)
437 .def(
"__iter__", iterator<This>())
439 .def(
"__repr__", __repr__<Type>)
442 .def(
"__str__", _VtStr<T>)
446#ifdef NUMERIC_OPERATORS
447#define ADDITION_OPERATOR
448#define SUBTRACTION_OPERATOR
449#define MULTIPLICATION_OPERATOR
450#define DIVISION_OPERATOR
451#define UNARY_NEG_OPERATOR
454#ifdef ADDITION_OPERATOR
455 VTOPERATOR_WRAPDECLARE(+,__add__,__radd__)
457#ifdef SUBTRACTION_OPERATOR
458 VTOPERATOR_WRAPDECLARE(-,__sub__,__rsub__)
460#ifdef MULTIPLICATION_OPERATOR
461 VTOPERATOR_WRAPDECLARE(*,__mul__,__rmul__)
463#ifdef DIVISION_OPERATOR
464 VTOPERATOR_WRAPDECLARE(/,__div__,__rdiv__)
467 VTOPERATOR_WRAPDECLARE(%,__mod__,__rmod__)
469#ifdef DOUBLE_MULT_OPERATOR
470 .def(self *
double())
471 .def(
double() * self)
473#ifdef DOUBLE_DIV_OPERATOR
474 .def(self /
double())
476#ifdef UNARY_NEG_OPERATOR
483 TfPyContainerConversions::from_python_sequence<
485 TfPyContainerConversions::
486 variable_capacity_all_items_convertible_policy>();
489 implicitly_convertible<This, TfSpan<Type> >();
490 implicitly_convertible<This, TfSpan<const Type> >();
493template <
class Array>
497 typedef typename Array::ElementType ElemType;
499 if (PySequence_Check(obj.
ptr())) {
500 Py_ssize_t len = PySequence_Length(obj.
ptr());
502 ElemType *elem = result.data();
503 for (Py_ssize_t i = 0; i != len; ++i) {
504 pxr_boost::python::handle<> h(PySequence_ITEM(obj.
ptr(), i));
506 if (PyErr_Occurred())
510 pxr_boost::python::extract<ElemType> e(h.get());
516 }
else if (PyIter_Check(obj.
ptr())) {
518 while (PyObject *item = PyIter_Next(obj.
ptr())) {
519 pxr_boost::python::handle<> h(item);
521 if (PyErr_Occurred())
525 pxr_boost::python::extract<ElemType> e(h.get());
528 result.push_back(e());
535template <
class Array,
class Iter>
537Vt_ConvertFromRange(Iter begin, Iter end)
539 typedef typename Array::ElementType ElemType;
540 Array result(distance(begin, end));
541 for (ElemType *e = result.data(); begin != end; ++begin) {
542 VtValue cast = VtValue::Cast<ElemType>(*begin);
552Vt_CastToArray(
VtValue const &v) {
558 }
else if (v.
IsHolding<std::vector<VtValue> >()) {
559 std::vector<VtValue>
const &vec = v.
UncheckedGet<std::vector<VtValue> >();
560 ret = Vt_ConvertFromRange<T>(vec.begin(), vec.end());
567void VtRegisterValueCastsFromPythonSequencesToArray()
570 VtValue::RegisterCast<TfPyObjWrapper, Array>(Vt_CastToArray<Array>);
571 VtValue::RegisterCast<std::vector<VtValue>, Array>(Vt_CastToArray<Array>);
574#define VT_WRAP_ARRAY(unused, elem) \
575 VtWrapArray< VtArray< VT_TYPE(elem) > >();
577PXR_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.